Compare commits

...

6 commits

Author SHA1 Message Date
79341f0a38 feat(pipeline): integrate profiles, layout, handoff, and provenance
All checks were successful
CI / unit (pull_request) Successful in 45s
CI / backend-e2e (pull_request) Successful in 1m20s
CI / dashboard-e2e (pull_request) Successful in 2m28s
2026-10-05 17:01:08 +01:00
446bbbe061 feat(bridge): shorts-to-long-form bridge + dashboard UI 2026-10-05 17:01:08 +01:00
2d77269337 feat(packaging): title validator + thumbnail concept roles + mobile safe areas 2026-10-05 17:01:08 +01:00
ba1d337f3a feat(layout): code/terminal vertical layout + screencast dead-wire fix 2026-10-05 17:01:08 +01:00
655cff2f64 feat(clips): word-aligned punch-ins + hook-first boundaries 2026-10-05 17:01:08 +01:00
ea251a1128 feat(profiles): channel profiles + shared prompt mapping 2026-10-05 17:01:08 +01:00
45 changed files with 6287 additions and 106 deletions

30
channels/cseea.json Normal file
View file

@ -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": []
}

30
channels/pedro.json Normal file
View file

@ -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": []
}

View file

@ -1,5 +1,5 @@
import os import os
from clipwright.pipeline import llm_backend from clipwright.pipeline import llm_backend, profiles
import re import re
import sys import sys
import uuid import uuid
@ -29,7 +29,7 @@ import httpx
from clipwright.media import recut from clipwright.media import recut
from clipwright.layouts import layout_ranges from clipwright.layouts import layout_ranges
from clipwright.api import media_auth from clipwright.api import media_auth
from clipwright.integrations import postiz from clipwright.integrations import postiz, youtube_data
from clipwright.core.paths import REPO_ROOT from clipwright.core.paths import REPO_ROOT
load_dotenv() load_dotenv()
@ -1518,6 +1518,11 @@ def _safe_under(base_dir: str, user_rel_path: str) -> Optional[str]:
class ProcessRequest(BaseModel): class ProcessRequest(BaseModel):
url: str url: str
# Channel profile slug (channels/<slug>.json); OPTIONAL per PLAN #1 v0.
channel: Optional[str] = None
# Target long-form video for the Shorts->long-form bridge copy/checklist
# (PLAN #6). OPTIONAL: without it the profile history is used.
related_video_url: Optional[str] = None
# Masks user:password credentials embedded in any URL (e.g. the residential # Masks user:password credentials embedded in any URL (e.g. the residential
# proxy URL that yt-dlp echoes in its verbose debug output) before the line is # proxy URL that yt-dlp echoes in its verbose debug output) before the line is
@ -1752,6 +1757,18 @@ async def get_config():
"localLlm": llm_backend.describe(), "localLlm": llm_backend.describe(),
} }
@app.get("/api/channels")
async def list_channels():
"""The channel profiles a job can be tagged with (PLAN #1).
Each entry is ``{"slug", "name"}`` for the dashboard's profile selector:
``slug`` is the ``channels/<slug>.json`` filename stem and ``name`` is the
profile's display name, falling back to the slug when the file omits it.
Malformed profile files are skipped by the loader, so the selector always
receives a usable list.
"""
return {"channels": profiles.list_profiles()}
async def _probe_youtube_quality(url: str) -> dict: async def _probe_youtube_quality(url: str) -> dict:
"""Run quality_probe.py in a worker thread; {} on any failure (fail-open).""" """Run quality_probe.py in a worker thread; {} on any failure (fail-open)."""
def _run(): def _run():
@ -1851,6 +1868,7 @@ def _reject_short_source(duration: float):
LAYOUT_ENV = { LAYOUT_ENV = {
"split": "SPLIT_LAYOUT", # two speakers stacked "split": "SPLIT_LAYOUT", # two speakers stacked
"screencast": "SCREENCAST_LAYOUT", # slides/screen share over the speaker "screencast": "SCREENCAST_LAYOUT", # slides/screen share over the speaker
"code": "CODE_LAYOUT", # IDE / terminal text column
"speaker_cut": "SPEAKER_CUT", # hard cuts to whoever is talking "speaker_cut": "SPEAKER_CUT", # hard cuts to whoever is talking
"punch_in": "PUNCH_IN", # small push on the clip's beats "punch_in": "PUNCH_IN", # small push on the clip's beats
} }
@ -1883,17 +1901,27 @@ def _upload_url_base(request):
@app.post("/api/uploads") @app.post("/api/uploads")
async def create_upload(request: Request): async def create_upload(request: Request):
"""Reserve an upload slot. Body (JSON, optional): {"filename": "..."}.""" """Reserve an upload slot. Body (JSON, optional): {"filename": "..."}.
``kind`` defaults to ``"video"`` (probed for a duration on PUT). A
``"handoff"`` slot carries a ZIP bundle (cadence manifest + transcript) and
is stored verbatim — see /api/process ``handoff_id``.
"""
user_id = await _owner_id(request) user_id = await _owner_id(request)
try: try:
body = await request.json() body = await request.json()
except Exception: except Exception:
body = {} body = {}
filename = os.path.basename(str((body or {}).get("filename") or "video.mp4")) or "video.mp4" body = body or {}
kind = str(body.get("kind") or "video").strip().lower()
if kind not in ("video", "handoff"):
raise HTTPException(status_code=400, detail="kind must be 'video' or 'handoff'")
filename = os.path.basename(str(body.get("filename") or "video.mp4")) or "video.mp4"
upload_id = str(uuid.uuid4()) upload_id = str(uuid.uuid4())
pending_uploads[upload_id] = { pending_uploads[upload_id] = {
"user_id": user_id, "user_id": user_id,
"filename": filename, "filename": filename,
"kind": kind,
"path": os.path.join(UPLOAD_DIR, f"pending_{upload_id}_{filename}"), "path": os.path.join(UPLOAD_DIR, f"pending_{upload_id}_{filename}"),
"created": time.time(), "created": time.time(),
"bytes": 0, "bytes": 0,
@ -1901,6 +1929,7 @@ async def create_upload(request: Request):
} }
return { return {
"upload_id": upload_id, "upload_id": upload_id,
"kind": kind,
"upload_url": f"{_upload_url_base(request)}/api/uploads/{upload_id}", "upload_url": f"{_upload_url_base(request)}/api/uploads/{upload_id}",
"method": "PUT", "method": "PUT",
"max_mb": MAX_FILE_SIZE_MB, "max_mb": MAX_FILE_SIZE_MB,
@ -1934,12 +1963,18 @@ async def put_upload(upload_id: str, request: Request):
os.remove(slot["path"]) os.remove(slot["path"])
raise HTTPException(status_code=400, detail="Empty body") raise HTTPException(status_code=400, detail="Empty body")
slot.update({"bytes": size, "complete": True}) slot.update({"bytes": size, "complete": True})
if slot.get("kind") == "handoff":
# A handoff slot holds a ZIP (manifest + transcript), not media: the
# duration probe below would reject it as "not a readable video".
return {"upload_id": upload_id, "kind": "handoff", "bytes": size,
"hint": "Now call /api/process with handoff_id (and your master video)."}
duration = await asyncio.get_event_loop().run_in_executor(None, _media_duration_seconds, slot["path"]) duration = await asyncio.get_event_loop().run_in_executor(None, _media_duration_seconds, slot["path"])
if duration <= 0: if duration <= 0:
os.remove(slot["path"]) os.remove(slot["path"])
slot["complete"] = False slot["complete"] = False
raise HTTPException(status_code=400, detail="The body is not a readable video file") raise HTTPException(status_code=400, detail="The body is not a readable video file")
return {"upload_id": upload_id, "bytes": size, "duration_seconds": round(duration, 1), return {"upload_id": upload_id, "kind": "video", "bytes": size,
"duration_seconds": round(duration, 1),
"hint": "Now call /api/process with upload_id."} "hint": "Now call /api/process with upload_id."}
@ -1983,6 +2018,106 @@ def _take_pending_upload(upload_id, user_id):
return slot return slot
_HANDOFF_SCHEMA = "clipwright.handoff/1"
def _handoff_member_name(name):
"""Basename of a ZIP member, normalized so no member can escape on extract."""
return os.path.basename(name.replace("\\", "/").rstrip("/"))
def _read_handoff_manifest(zf, members):
"""(member_name, manifest_dict) for the bundle's manifest, or (None, None).
Prefers the documented ``*.handoff.json`` name, then falls back to any JSON
member carrying the handoff schema marker.
"""
for name in members:
if name.endswith(".handoff.json"):
try:
data = json.loads(zf.read(members[name].filename).decode("utf-8"))
except (json.JSONDecodeError, UnicodeDecodeError):
continue
if isinstance(data, dict):
return name, data
for name, info in members.items():
if not name.endswith(".json"):
continue
try:
data = json.loads(zf.read(info.filename).decode("utf-8"))
except (json.JSONDecodeError, UnicodeDecodeError):
continue
if isinstance(data, dict) and data.get("schema") == _HANDOFF_SCHEMA:
return name, data
return None, None
def _stage_handoff_bundle(bundle_path, job_output_dir):
"""Stage an uploaded cadence handoff ZIP into the job dir.
Writes the transcript to ``<job>/source_transcript.json`` and a manifest
pointing at it to ``<job>/cadence_handoff.json``, then returns the latter's
path (handed to the child as ``--handoff``). Only the manifest and the
transcript it references are read; ``sources[].path`` is never opened (they
are emitter-local), and member names are reduced to basenames so a hostile
archive cannot read or write outside the job dir.
"""
if not zipfile.is_zipfile(bundle_path):
raise HTTPException(
status_code=400,
detail="Handoff bundle must be a ZIP containing the manifest and transcript.json")
limit_bytes = MAX_FILE_SIZE_MB * 1024 * 1024
try:
with zipfile.ZipFile(bundle_path) as zf:
members = {}
for info in zf.infolist():
if info.is_dir():
continue
if limit_bytes and info.file_size > limit_bytes:
raise HTTPException(status_code=413, detail="Handoff bundle entry too large")
members[_handoff_member_name(info.filename)] = info
manifest_name, manifest = _read_handoff_manifest(zf, members)
if manifest_name is None:
raise HTTPException(
status_code=400,
detail="Handoff bundle has no manifest (expected a *.handoff.json "
f"with schema {_HANDOFF_SCHEMA!r})")
ref = manifest.get("transcript")
ref = ref.get("path") if isinstance(ref, dict) else None
if not ref:
raise HTTPException(status_code=400,
detail="Handoff manifest has no transcript.path")
transcript_name = _handoff_member_name(str(ref))
info = members.get(transcript_name)
if info is None:
raise HTTPException(
status_code=400,
detail=f"Handoff transcript {ref!r} is not in the bundle")
transcript_bytes = zf.read(info.filename)
except HTTPException:
raise
except zipfile.BadZipFile as e:
raise HTTPException(status_code=400, detail=f"Unreadable handoff bundle: {e}")
try:
transcript = json.loads(transcript_bytes.decode("utf-8"))
except (json.JSONDecodeError, UnicodeDecodeError) as e:
raise HTTPException(status_code=400, detail=f"Malformed handoff transcript: {e}")
if not isinstance(transcript, dict) or not transcript.get("segments"):
raise HTTPException(status_code=400, detail="Handoff transcript has no segments")
transcript_path = os.path.join(job_output_dir, "source_transcript.json")
with open(transcript_path, "wb") as out:
out.write(transcript_bytes)
manifest = dict(manifest)
manifest["transcript"] = dict(manifest.get("transcript") or {})
manifest["transcript"]["path"] = "source_transcript.json"
manifest_path = os.path.join(job_output_dir, "cadence_handoff.json")
with open(manifest_path, "w", encoding="utf-8") as f:
json.dump(manifest, f, indent=2)
return manifest_path
def layout_env(requested): def layout_env(requested):
"""Env overrides for the layouts this job allows. Unknown names are ignored """Env overrides for the layouts this job allows. Unknown names are ignored
rather than rejected: a newer dashboard must not break an older API. rather than rejected: a newer dashboard must not break an older API.
@ -2032,6 +2167,9 @@ async def process_endpoint(
captions: Optional[str] = Form(None), captions: Optional[str] = Form(None),
upload_id: Optional[str] = Form(None), upload_id: Optional[str] = Form(None),
max_minutes: Optional[str] = Form(None), max_minutes: Optional[str] = Form(None),
channel: Optional[str] = Form(None),
handoff_id: Optional[str] = Form(None),
related_video_url: Optional[str] = Form(None),
): ):
api_key = await resolve_gemini(request) api_key = await resolve_gemini(request)
if not api_key and not llm_backend.active(): if not api_key and not llm_backend.active():
@ -2064,6 +2202,9 @@ async def process_endpoint(
captions = body.get("captions") captions = body.get("captions")
upload_id = body.get("upload_id") upload_id = body.get("upload_id")
max_minutes = body.get("max_minutes") max_minutes = body.get("max_minutes")
channel = body.get("channel")
handoff_id = body.get("handoff_id")
related_video_url = body.get("related_video_url")
# Normalize output format (auto = keep pipeline default). # Normalize output format (auto = keep pipeline default).
if output_format not in ("vertical", "horizontal", "square"): if output_format not in ("vertical", "horizontal", "square"):
@ -2154,6 +2295,31 @@ async def process_endpoint(
# fails instead. setdefault, so an explicit PYTHONIOENCODING still wins. # fails instead. setdefault, so an explicit PYTHONIOENCODING still wins.
env.setdefault("PYTHONIOENCODING", "utf-8") env.setdefault("PYTHONIOENCODING", "utf-8")
# Per-channel profile (PLAN #1 v0). Validate the slug now so a typo is a
# clear 400 instead of a job that dies in the subprocess, then hand the
# child just the slug -- generation behaviour is unchanged until later items.
channel_slug = str(channel).strip() if channel else ""
if channel_slug:
from clipwright.pipeline.profiles import ProfileError, load_profile
try:
load_profile(channel_slug)
except ProfileError as e:
raise HTTPException(status_code=400, detail=f"Invalid channel profile: {e}")
env["CHANNEL_PROFILE"] = channel_slug
print(f"[channel] job={job_id} profile={channel_slug}")
# Shorts -> long-form bridge target (PLAN #6). Explicit URL only; the
# per-clip copy falls back to the profile's published_video_history when it
# is absent. Passed as a CLI flag, so a value that looks like an option can
# never be misread (argv list, no shell).
bridge_target = str(related_video_url).strip() if related_video_url else ""
if bridge_target:
if not bridge_target.startswith(("http://", "https://")):
raise HTTPException(status_code=400,
detail="related_video_url must be an http(s) URL")
cmd.extend(["--longform-url", bridge_target])
print(f"[bridge] job={job_id} longform={bridge_target}")
# Optional layouts are per job. The renderer reads these at import time in # Optional layouts are per job. The renderer reads these at import time in
# the subprocess, so they must be set before Popen. # the subprocess, so they must be set before Popen.
chosen = layout_env(layouts) chosen = layout_env(layouts)
@ -2281,6 +2447,20 @@ async def process_endpoint(
cmd.extend(["-i", input_path]) cmd.extend(["-i", input_path])
# Cadence handoff (PLAN #8): the bundle was uploaded to its own slot. Stage
# the manifest + transcript in the job dir and point the child at it; the
# slot is only consumed once staging succeeded. Never touches sources[].path.
if handoff_id:
slot = _take_pending_upload(handoff_id, await _owner_id(request))
manifest_path = _stage_handoff_bundle(slot["path"], job_output_dir)
pending_uploads.pop(handoff_id, None)
try:
os.remove(slot["path"])
except OSError:
pass
cmd.extend(["--handoff", manifest_path])
print(f"[handoff] job={job_id} manifest={os.path.basename(manifest_path)}")
cmd.extend(["-o", job_output_dir]) cmd.extend(["-o", job_output_dir])
if output_format and output_format != "auto": if output_format and output_format != "auto":
cmd.extend(["--format", output_format]) cmd.extend(["--format", output_format])
@ -2974,6 +3154,140 @@ async def get_clip_edl(job_id: str, clip_index: int, request: Request):
} }
# --- Shorts -> long-form bridge (PLAN #6) ----------------------------------
class BridgeCommentRequest(BaseModel):
"""Explicit opt-in to post a clip's first comment on YouTube.
``video_id`` is the published Short's id; this server does not track the id
Postiz assigned at publish time, so the caller supplies it. ``text``
defaults to the clip's generated ``first_comment``.
"""
video_id: str
text: Optional[str] = None
def _clip_metadata(job_id: str, clip_index: int) -> Optional[dict]:
"""The raw clip dict from a job's metadata.json (or None)."""
output_dir = os.path.join(OUTPUT_DIR, job_id)
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
if not json_files:
return None
try:
with open(json_files[0], "r") as f:
data = json.load(f)
except (OSError, ValueError):
return None
clips = data.get("shorts", [])
if clip_index < 0 or clip_index >= len(clips):
return None
return clips[clip_index]
@app.get("/api/clip/{job_id}/{clip_index}/bridge")
async def get_clip_bridge(job_id: str, clip_index: int, request: Request):
"""The generated Shorts->long-form copy and manual Studio checklist.
Both the "Related video" link and comment pinning are Studio-UI only, so
this always carries the manual steps; ``manual_pin_required`` is always
true. ``comment_api_configured`` says whether the opt-in comment endpoint
below would work on this server.
"""
job = _job_record(job_id)
if job is None:
raise HTTPException(status_code=404, detail="Job not found")
await _assert_job_owner(request, job)
clip = _clip_metadata(job_id, clip_index)
if clip is None:
raise HTTPException(status_code=404, detail="Clip not found")
return {
"job_id": job_id,
"clip_index": clip_index,
"description_bridge": clip.get("description_bridge") or "",
"first_comment": clip.get("first_comment") or "",
"related_video_url": clip.get("related_video_url"),
"checklist": clip.get("checklist") or [],
"manual_pin_required": True,
"comment_api_configured": youtube_data.is_configured(),
}
@app.get("/api/clip/{job_id}/{clip_index}/provenance")
async def get_clip_provenance(job_id: str, clip_index: int, request: Request):
"""The versioned retention provenance record of one clip (PLAN #10).
Instrumentation only: a stable read of the profile, predicted score, start
boundary path, bridge target and publish target the pipeline recorded when
it wrote the clip's metadata. The same object also rides along inside the
job result's clip dicts; this endpoint is the explicit, versioned handle
the future retention/analytics loop can pull. A clip predating the
instrumentation has no record, so this answers 404 rather than inventing one.
"""
job = _job_record(job_id)
if job is None:
raise HTTPException(status_code=404, detail="Job not found")
await _assert_job_owner(request, job)
clip = _clip_metadata(job_id, clip_index)
if clip is None:
raise HTTPException(status_code=404, detail="Clip not found")
provenance = clip.get("provenance")
if not isinstance(provenance, dict):
raise HTTPException(
status_code=404, detail="No provenance recorded for this clip")
return {
"job_id": job_id,
"clip_index": clip_index,
"schema_version": provenance.get("schema_version"),
"provenance": provenance,
}
@app.post("/api/clip/{job_id}/{clip_index}/bridge/comment")
async def post_clip_bridge_comment(job_id: str, clip_index: int,
req: BridgeCommentRequest, request: Request):
"""Post the clip's first comment via the YouTube Data API (opt-in).
Never automatic: the caller triggers it explicitly for one published video.
Pinning stays manual (no API). Returns a clear 400 when the server has no
YouTube OAuth credentials configured.
"""
job = _job_record(job_id)
if job is None:
raise HTTPException(status_code=404, detail="Job not found")
await _assert_job_owner(request, job)
clip = _clip_metadata(job_id, clip_index)
if clip is None:
raise HTTPException(status_code=404, detail="Clip not found")
if not youtube_data.is_configured():
raise HTTPException(
status_code=400,
detail=("YouTube Data API is not configured on this server; set "
f"{youtube_data.CLIENT_ID_ENV}, {youtube_data.CLIENT_SECRET_ENV} "
f"and {youtube_data.REFRESH_TOKEN_ENV} to enable first-comment posting."),
)
text = (req.text or clip.get("first_comment") or "").strip()
if not text:
raise HTTPException(status_code=400, detail="No comment text to post")
if not str(req.video_id).strip():
raise HTTPException(status_code=400, detail="video_id is required")
try:
result = await asyncio.to_thread(
youtube_data.post_first_comment, req.video_id, text)
except youtube_data.YoutubeDataError as exc:
raise HTTPException(status_code=exc.status_code, detail=exc.detail)
return {
"posted": True,
"video_id": req.video_id,
"comment_id": (result or {}).get("id"),
# A clear reminder that the API cannot pin.
"manual_pin_required": True,
}
class RerenderSegment(BaseModel): class RerenderSegment(BaseModel):
start: float start: float
end: float end: float
@ -4473,12 +4787,29 @@ async def thumbnail_upload(
return {"session_id": session_id} return {"session_id": session_id}
def _channel_profile(channel):
"""Resolve an optional channel field to a Profile (PLAN #1).
Returns None when no channel was given, so a profile-less request behaves
exactly as it did before profiles existed. A bad slug is a clear 400.
"""
slug = str(channel).strip() if channel else ""
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=f"Invalid channel profile: {e}")
@app.post("/api/thumbnail/analyze") @app.post("/api/thumbnail/analyze")
async def thumbnail_analyze( async def thumbnail_analyze(
request: Request, request: Request,
file: Optional[UploadFile] = File(None), file: Optional[UploadFile] = File(None),
url: Optional[str] = Form(None), url: Optional[str] = Form(None),
session_id: Optional[str] = Form(None), session_id: Optional[str] = Form(None),
channel: Optional[str] = Form(None),
x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key")
): ):
"""Analyze a video and suggest viral YouTube titles.""" """Analyze a video and suggest viral YouTube titles."""
@ -4486,6 +4817,9 @@ async def thumbnail_analyze(
if not api_key: if not api_key:
raise gemini_missing_error() raise gemini_missing_error()
# PLAN #1: resolve the channel before any download/upload so a bad slug
# fails fast with a 400 instead of after the work.
profile = _channel_profile(channel)
pre_transcript = None pre_transcript = None
# Check for pre-existing session with background Whisper # Check for pre-existing session with background Whisper
@ -4536,7 +4870,10 @@ async def thumbnail_analyze(
try: try:
# Run analysis in thread pool (skips Whisper if pre_transcript is available) # Run analysis in thread pool (skips Whisper if pre_transcript is available)
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
result = await loop.run_in_executor(None, analyze_video_for_titles, api_key, video_path, pre_transcript) result = await loop.run_in_executor(
None,
functools.partial(analyze_video_for_titles, api_key, video_path,
pre_transcript, profile=profile))
# Store/update session context # Store/update session context
if session_id not in thumbnail_sessions: if session_id not in thumbnail_sessions:
@ -4647,6 +4984,7 @@ async def thumbnail_generate(
count: int = Form(3), count: int = Form(3),
burn_text: bool = Form(True), burn_text: bool = Form(True),
frame: str = Form(""), frame: str = Form(""),
channel: Optional[str] = Form(None),
face: Optional[UploadFile] = File(None), face: Optional[UploadFile] = File(None),
background: Optional[UploadFile] = File(None), background: Optional[UploadFile] = File(None),
): ):
@ -4661,6 +4999,9 @@ async def thumbnail_generate(
if not api_key: if not api_key:
raise gemini_missing_error() raise gemini_missing_error()
# PLAN #1: resolve the channel up front; a bad slug is a 400, not a 500.
profile = _channel_profile(channel)
# The session carries someone's transcript, titles and frames: only its # The session carries someone's transcript, titles and frames: only its
# owner may generate from it. # owner may generate from it.
_sess = thumbnail_sessions.get(session_id) _sess = thumbnail_sessions.get(session_id)
@ -4713,7 +5054,7 @@ async def thumbnail_generate(
generate_thumbnail, api_key, title, session_id, face_path, bg_path, generate_thumbnail, api_key, title, session_id, face_path, bg_path,
extra_prompt, count, video_context, burn_text=burn_text, extra_prompt, count, video_context, burn_text=burn_text,
thumbnail_text_hint=text_hint, language=language, thumbnail_text_hint=text_hint, language=language,
frame_reference=frame_reference), frame_reference=frame_reference, profile=profile),
) )
if not thumbnails: if not thumbnails:
@ -4765,6 +5106,7 @@ async def thumbnail_frames(session_id: str, request: Request):
class ThumbnailDescribeRequest(BaseModel): class ThumbnailDescribeRequest(BaseModel):
session_id: str session_id: str
title: str title: str
channel: Optional[str] = None
@app.post("/api/thumbnail/describe") @app.post("/api/thumbnail/describe")
async def thumbnail_describe( async def thumbnail_describe(
@ -4776,6 +5118,9 @@ async def thumbnail_describe(
if not api_key: if not api_key:
raise gemini_missing_error() raise gemini_missing_error()
# PLAN #1: resolve the channel before the try so a bad slug is a 400.
profile = _channel_profile(req.channel)
if req.session_id not in thumbnail_sessions: if req.session_id not in thumbnail_sessions:
raise HTTPException(status_code=404, detail="Session not found") raise HTTPException(status_code=404, detail="Session not found")
@ -4789,12 +5134,15 @@ async def thumbnail_describe(
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
result = await loop.run_in_executor( result = await loop.run_in_executor(
None, None,
generate_youtube_description, functools.partial(
api_key, generate_youtube_description,
req.title, api_key,
segments, req.title,
session.get("language", "en"), segments,
session.get("video_duration", 0) session.get("language", "en"),
session.get("video_duration", 0),
profile=profile,
),
) )
return {"description": result.get("description", "")} return {"description": result.get("description", "")}

View file

@ -41,6 +41,8 @@ from urllib.parse import parse_qs, urlparse
from fastapi import APIRouter, HTTPException, Request from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel from pydantic import BaseModel
from clipwright.media import title_validation
router = APIRouter() router = APIRouter()
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
@ -476,6 +478,7 @@ class MetadataRequest(BaseModel):
topic: str topic: str
keyword: Optional[str] = "" keyword: Optional[str] = ""
audience: Optional[str] = "" audience: Optional[str] = ""
channel: Optional[str] = None
_COMMON_RULES = """ _COMMON_RULES = """
@ -543,8 +546,13 @@ def _clean(s: str) -> str:
return re.sub(r"\s*—\s*", ", ", (s or "")).strip() return re.sub(r"\s*—\s*", ", ", (s or "")).strip()
def shape_result(mode: str, data: dict) -> dict: def shape_result(mode: str, data: dict, profile=None) -> dict:
"""Validate and tidy the model's JSON into what the page renders.""" """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": if mode == "titles":
items = [] items = []
for t in (data.get("titles") or [])[:12]: 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]}) items.append({"title": title, "angle": _clean(str(t.get("angle", "")))[:40]})
if not items: if not items:
raise ValueError("no titles") 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": if mode == "description":
desc = _clean(str(data.get("description", "")))[:5000] desc = _clean(str(data.get("description", "")))[:5000]
if not desc: if not desc:
@ -576,6 +588,37 @@ def shape_result(mode: str, data: dict) -> dict:
return {"tags": tags, "characters": len(",".join(tags))} 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(): def _gemini_key():
return os.environ.get("GEMINI_API_KEY", "").strip() or None 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={ raise HTTPException(status_code=503, detail={
"code": "not_configured", "message": "This tool needs a Gemini API key on the server."}) "code": "not_configured", "message": "This tool needs a Gemini API key on the server."})
_enforce("metadata", request) _enforce("metadata", request)
profile = _profile_for_channel(payload.channel)
prompt = build_prompt(mode, topic.replace("{", "(").replace("}", ")"), keyword, audience) prompt = build_prompt(mode, topic.replace("{", "(").replace("}", ")"), keyword, audience)
last = None last = None
for _ in range(2): for _ in range(2):
try: try:
data = await asyncio.wait_for(asyncio.to_thread(_generate, prompt), timeout=40) 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: except asyncio.TimeoutError:
last = "timeout" last = "timeout"
break break

View file

@ -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 {}

View file

@ -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)

View file

@ -64,6 +64,7 @@ SAMPLE_WIDTH = int(os.environ.get("LAYOUT_SAMPLE_WIDTH", "1024"))
DECISION_FLAGS = { DECISION_FLAGS = {
"none": [], "none": [],
"screencast": ["screencast_layout"], "screencast": ["screencast_layout"],
"code": ["code_layout"],
"split": ["split_layout", "active_speaker"], "split": ["split_layout", "active_speaker"],
} }
@ -83,11 +84,13 @@ def apply(decision):
must not quietly undo that. must not quietly undo that.
""" """
from clipwright.layouts import active_speaker from clipwright.layouts import active_speaker
from clipwright.layouts import code_layout
from clipwright.layouts import screencast_layout from clipwright.layouts import screencast_layout
from clipwright.layouts import split_layout from clipwright.layouts import split_layout
modules = {"split_layout": split_layout, modules = {"split_layout": split_layout,
"screencast_layout": screencast_layout, "screencast_layout": screencast_layout,
"code_layout": code_layout,
"active_speaker": active_speaker} "active_speaker": active_speaker}
touched = [] touched = []

View file

@ -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 x-only to w/h/x/y, so it composes with the camera trajectory instead of fighting
it. Off by default (``PUNCH_IN=1``). it. Off by default (``PUNCH_IN=1``).
Beat times come from the audio envelope. The transcript would be a better Beat times come from the audio envelope, aligned to the clip-relative word
source (punch on the hook word, not on the loudest syllable), and render() has onsets the transcript provides (``emphasis_times(word_times=...)``). The
no transcript today — ``emphasis_times`` is a plain list of seconds, so wiring envelope finds the emphasis; the word onset says exactly when it started, so
main.py's word timings in later needs no change here. 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 os
import numpy as np import numpy as np
@ -59,6 +62,11 @@ BEAT_WINDOW = 0.2
MIN_GAP_SECONDS = 18.0 MIN_GAP_SECONDS = 18.0
BEAT_PROMINENCE = 0.60 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): def _ease(t):
"""Smoothstep on [0, 1]. Linear ramps look mechanical at this duration.""" """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 return lines
def emphasis_times(video_path, duration, window=BEAT_WINDOW, def _snap_to_word(t, words, snap):
min_gap=MIN_GAP_SECONDS, prominence=BEAT_PROMINENCE): """``t`` moved to the closest onset in the sorted ``words``, if within
"""Seconds where the audio leaps above its own baseline. ``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 from clipwright.layouts import active_speaker
envelope = active_speaker.audio_envelope(video_path, 0.0, duration, envelope = active_speaker.audio_envelope(video_path, 0.0, duration,
window_s=window) window_s=window)
if not envelope: audio_beats = []
return [] 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) return merge_beats(audio_beats, word_times, min_gap=min_gap)
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

View file

@ -23,6 +23,7 @@ import tempfile
from clipwright.layouts import active_speaker from clipwright.layouts import active_speaker
from clipwright.layouts import camera_inset from clipwright.layouts import camera_inset
from clipwright.layouts import code_layout
from clipwright.layouts import punch_in from clipwright.layouts import punch_in
from clipwright.layouts import screencast_layout from clipwright.layouts import screencast_layout
from clipwright.layouts import layout_ranges 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, 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). """Full v2 reframe of one clip. Raises on failure (caller falls back).
``content_ranges`` comes from screencast_layout.detect_content_ranges() on ``content_ranges`` comes from screencast_layout.detect_content_ranges() on
the SOURCE video, already translated into this clip's timeline. None or [] the SOURCE video, already translated into this clip's timeline. When it is
means the layout never triggers, which is the default. 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) ``force_strategy`` ('WIDE' / 'TRACK' / any layout the render loop knows)
applies that layout to EVERY scene, skipping the classifier and the layout 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 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 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. 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 from clipwright.pipeline import main as m
auto_content_ranges = content_ranges is None
content_ranges = content_ranges or [] content_ranges = content_ranges or []
print(" 🚀 Reframe engine v2 (ffmpeg-native render)") 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: if alternates:
print(f" 🎬 Speaker-cut layout on {len(alternates)} scene(s)") 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 # 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 # faces beside a chart still means the chart is what the shot is about, and
# stacking the two speakers would crop it away entirely. # 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: if content_ranges:
for scene_idx, (plan, centre) in screencast_layout.detect_screencast_scenes( for scene_idx, (plan, centre) in screencast_layout.detect_screencast_scenes(
input_video, scenes, strategies, content_ranges).items(): 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 # An inset beats both screen plans: it is the only one that can show
# the screen whole AND the person at a readable size. # the screen whole AND the person at a readable size.
if inset: 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 are found once per clip; each scene takes the ones inside it.
beats = [] beats = []
if punch_in.ENABLED: 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: if beats:
print(f" 🔍 Punch-in on {len(beats)} beat(s)") 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] left, right = splits[start_f]
graph = split_layout.split_filtergraph( graph = split_layout.split_filtergraph(
orig_w, orig_h, out_w, out_h, left, right) 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': elif strategy == 'GENERAL':
graph = general_filtergraph(out_w, out_h, graph = general_filtergraph(out_w, out_h,
orig_w=orig_w, orig_h=orig_h) orig_w=orig_w, orig_h=orig_h)

View file

@ -10,6 +10,8 @@ from google.genai import types
from google.genai import errors as genai_errors from google.genai import errors as genai_errors
from PIL import Image, ImageDraw, ImageFont, ImageFilter from PIL import Image, ImageDraw, ImageFont, ImageFilter
from clipwright.core.paths import FONTS_DIR 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 # Text/analysis model (titles, concepts, description). Deliberately NOT tied to
# GEMINI_MODEL: the pipeline runs flash-lite for a closed-choice layout pick, # 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") THUMB_FONT = str(FONTS_DIR / "Anton-Regular.ttf")
TEXT_POSITIONS = ("left", "right", "top", "bottom") 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): def _parse_json(text):
"""Gemini JSON, tolerant of code fences and prose around the object.""" """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 # 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. Suggests YouTube titles from the transcript plus a handful of frames.
Two calls: a wide brainstorm, then a critic that scores and picks a 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. 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", Returns: { "titles", "thumbnail_texts", "transcript_summary", "language",
"segments", "video_duration", "recommended" } "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 video_duration = segments[-1]["end"] if segments else 0
# Enough transcript for a title; a 3-hour podcast does not need all of it. # Enough transcript for a title; a 3-hour podcast does not need all of it.
transcript_text = transcript.get("text", "")[:60000] 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. 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. - Put the main keyword / subject in the first 3 words.
- Be specific to THIS video: names, numbers, tools, places from the transcript. Nothing generic. - 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. - No ALL CAPS words, at most one exclamation mark, no emojis.
{channel_rules}
OUTPUT JSON: OUTPUT JSON:
{{ {{
"transcript_summary": "...", "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". 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. Pick the top 2 and explain in one sentence each why they will win the click.
{channel_rules}
OUTPUT JSON: OUTPUT JSON:
{{ {{
"titles": ["...", ... 10 items], "titles": ["...", ... 10 items],
@ -166,21 +184,50 @@ OUTPUT JSON:
}}""" }}"""
print("🧐 [Thumbnail] Scoring titles...") 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 = [str(t) for t in picked.get("thumbnail_texts", [])][:len(titles)]
thumbnail_texts += [""] * (len(titles) - len(thumbnail_texts)) thumbnail_texts += [""] * (len(titles) - len(thumbnail_texts))
return { return {
@ -190,9 +237,7 @@ OUTPUT JSON:
"language": language, "language": language,
"segments": segments, "segments": segments,
"video_duration": video_duration, "video_duration": video_duration,
"recommended": [r for r in picked.get("recommended", []) "recommended": picked.get("recommended", []),
if isinstance(r, dict) and isinstance(r.get("index"), int)
and 0 <= r["index"] < len(titles)],
} }
@ -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="", 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 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 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. 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, " 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)." "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}"' hint_line = (f'\nSUGGESTED THUMBNAIL TEXT (use it for the first concept unless it is poor): "{thumbnail_text_hint}"'
if thumbnail_text_hint else "") if thumbnail_text_hint else "")
extra_line = f"\nMANDATORY USER INSTRUCTIONS (override everything else):\n{extra_prompt}\n" if extra_prompt 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. prompt = f"""You are a YouTube thumbnail art director. Design {count} DIFFERENT thumbnail concepts for this video.
VIDEO TITLE: "{title}" 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. 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. 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: 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": 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_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). - "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. - "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. - 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. - "why": one short sentence on why this earns the click.
OUTPUT JSON: 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( response = client.models.generate_content(
model=TEXT_MODEL, model=TEXT_MODEL,
@ -416,32 +468,96 @@ OUTPUT JSON:
except (json.JSONDecodeError, AttributeError): except (json.JSONDecodeError, AttributeError):
print(f"⚠️ [Thumbnail] Concept JSON unreadable, using a generic concept: {getattr(response, 'text', '')[:200]}") print(f"⚠️ [Thumbnail] Concept JSON unreadable, using a generic concept: {getattr(response, 'text', '')[:200]}")
concepts = [] 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=""): # #4: every concept declares the job it does for the click, and the set must
"""Clamp model output to what the renderer accepts and pad to `count`.""" # 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 = [] cleaned = []
for c in concepts: for c in concepts:
if not isinstance(c, dict) or not c.get("scene"): if not isinstance(c, dict) or not c.get("scene"):
continue continue
role = c.get("role") if c.get("role") in CONCEPT_ROLES else None
cleaned.append({ cleaned.append({
"text": str(c.get("text") or thumbnail_text_hint or "").strip().upper()[:40], "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_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", "text_color": "yellow" if c.get("text_color") == "yellow" else "white",
"role": role,
"scene": str(c["scene"]), "scene": str(c["scene"]),
"why": str(c.get("why", "")), "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: while len(cleaned) < count:
cleaned.append({ role = order[len(cleaned) % len(order)]
"text": thumbnail_text_hint.upper()[:40], cleaned.append(_fallback_concept(title, thumbnail_text_hint, role))
"text_position": "left", cleaned = cleaned[:count]
"text_color": "white",
"scene": (f"A bold, high-contrast YouTube thumbnail scene for a video titled '{title}'. " if count < 2:
"Dramatic lighting, vibrant colours, the left third is clean dark negative space."), return cleaned
"why": "fallback",
}) present = {c["role"] for c in cleaned}
return cleaned[:count] 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): def _wrap_lines(draw, text, font, max_width):
@ -502,8 +618,46 @@ def burn_thumbnail_text(img, text, position="left", color="white"):
else: else:
x0, y0 = int(W * 0.04), H - total_h - int(H * 0.06) - top_pad 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): 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)) shadow = Image.new("RGBA", img.size, (0, 0, 0, 0))
sdraw = ImageDraw.Draw(shadow) 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, 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, 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. Generates `count` thumbnails, each from its own concept, in parallel.
frame_reference: {"path", "face"} from extract_face_frames, used as the frame_reference: {"path", "face"} from extract_face_frames, used as the
person reference when the user picked a frame instead of uploading a photo. 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). Returns [{"url", "text", "why"}] (only the ones that rendered).
""" """
client = genai.Client(api_key=api_key) 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( concepts = plan_thumbnail_concepts(
client, title, count, video_context=video_context, extra_prompt=extra_prompt, 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): for i, c in enumerate(concepts):
print(f"🎨 [Thumbnail] Concept {i + 1}: \"{c['text']}\" ({c['text_position']}) - {c['why']}") 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 fallback = True
print(f"✅ [Thumbnail] Saved: {out_path}") print(f"✅ [Thumbnail] Saved: {out_path}")
return {"url": f"/thumbnails/{session_id}/{os.path.basename(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: except Exception as e:
print(f"❌ [Thumbnail] Generation {i + 1} failed: {e}") print(f"❌ [Thumbnail] Generation {i + 1} failed: {e}")
return {"error": str(e)} return {"error": str(e)}
@ -739,9 +897,12 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag
# Description # 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. 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" } Returns: { "description": "full description text with chapters" }
""" """
client = genai.Client(api_key=api_key) 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) dur_secs = int(video_duration % 60)
duration_str = f"{dur_mins}:{dur_secs:02d}" 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. prompt = f"""You are a YouTube SEO expert. Generate a complete YouTube video description for the following video.
VIDEO TITLE: "{title}" VIDEO TITLE: "{title}"
@ -783,7 +947,7 @@ REQUIREMENTS:
- Place chapters in their own section with a blank line before and after - Place chapters in their own section with a blank line before and after
5. Add 5-10 relevant hashtags at the end 5. Add 5-10 relevant hashtags at the end
6. Keep the total description under 5000 characters 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.""" 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...") print("🤖 [Thumbnail] Generating YouTube description with chapters...")

View file

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

View file

@ -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 "<paste the long-form video URL>"
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,
}

View file

@ -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. 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. # USD per 1M tokens (input, output incl. thinking), from ai.google.dev pricing.
MODEL_PRICES = { MODEL_PRICES = {
"gemini-3.5-flash": (1.50, 9.00), "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: if new_end <= new_start or new_end - new_start < min_duration:
return original return original
return (round(new_start, 3), round(new_end, 3)) 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)

View file

@ -157,6 +157,13 @@ Pick ONE layout:
in both runs, while overall accuracy fell from 92% to 83-85%. camera_inset.py in both runs, while overall accuracy fell from 92% to 83-85%. camera_inset.py
finds the same five geometrically with no false positives, so that question is finds the same five geometrically with no false positives, so that question is
answered downstream instead of being asked here.) answered downstream instead of being asked here.)
- "code": a screen recording of code — an IDE or a terminal — where the viewer
must read the source itself (a programming tutorial, a live debug, a shell
session). ONLY when monospaced text fills the screen and reading it is the
point; a slide or a spreadsheet is "screencast", not this. This option is
UNVALIDATED: it was added for a CODE layout that is off by default
(CODE_LAYOUT) and must be shadow-run on a corpus before it is relied on. When
unsure, answer "none" or "screencast".
- "split": stack two people. ONLY when two people are visible IN THE SAME SHOT - "split": stack two people. ONLY when two people are visible IN THE SAME SHOT
at the same time in most frames, talking to each other. Frames that alternate at the same time in most frames, talking to each other. Frames that alternate
between one-person close-ups are NOT this, however many people appear. between one-person close-ups are NOT this, however many people appear.
@ -323,7 +330,7 @@ COPY RULES — ALL text fields (descriptions, title, hook) MUST be written in TR
- `why`: one sentence, max 20 words, naming what makes THIS moment worth a - `why`: one sentence, max 20 words, naming what makes THIS moment worth a
clip — the specific hook, claim, number or payoff, not the topic. clip — the specific hook, claim, number or payoff, not the topic.
TRANSCRIPT_LANGUAGE: {language} {profile_rules}TRANSCRIPT_LANGUAGE: {language}
VIDEO_DURATION_SECONDS: {video_duration} VIDEO_DURATION_SECONDS: {video_duration}
CANDIDATE_WINDOWS_JSON: CANDIDATE_WINDOWS_JSON:
{windows_json} {windows_json}

View file

@ -24,7 +24,7 @@ import json
import os import os
from typing import Optional from typing import Optional
SCREEN_LAYOUTS = {"screencast", "wide", "inset"} SCREEN_LAYOUTS = {"screencast", "code", "wide", "inset"}
FRAMES = int(os.environ.get("HOOK_GROUNDING_FRAMES", "3")) FRAMES = int(os.environ.get("HOOK_GROUNDING_FRAMES", "3"))
WIDTH = int(os.environ.get("HOOK_GROUNDING_WIDTH", "1024")) WIDTH = int(os.environ.get("HOOK_GROUNDING_WIDTH", "1024"))
# Ignore a blip: the screen stretches must cover this share of the clip. # Ignore a blip: the screen stretches must cover this share of the clip.

View file

@ -21,12 +21,17 @@ from google import genai
from google.genai import types as genai_types from google.genai import types as genai_types
from clipwright.media import frame_sampler from clipwright.media import frame_sampler
from clipwright.media.subtitles import merge_continuation_words
from clipwright.pipeline import bridge
from clipwright.pipeline import gemini_worker from clipwright.pipeline import gemini_worker
from clipwright.pipeline import hook_grounding from clipwright.pipeline import hook_grounding
from clipwright.pipeline.profiles import ProfileError, load_profile
from clipwright.pipeline import profile_prompts
from clipwright.layouts import layout_picker from clipwright.layouts import layout_picker
from clipwright.pipeline import llm_backend from clipwright.pipeline import llm_backend
from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_count_targets, from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_count_targets,
clip_duration_bounds, dedupe_overlapping, clip_duration_bounds, dedupe_overlapping,
find_hook_start, hook_first_enabled,
score_batches, shortlist_target, score_batches, shortlist_target,
snap_clip_to_words, trim_to_best) snap_clip_to_words, trim_to_best)
from clipwright.media.ffmpeg_utils import (video_encode_args, cut_clip, from clipwright.media.ffmpeg_utils import (video_encode_args, cut_clip,
@ -43,6 +48,11 @@ load_dotenv()
# --- Constants --- # --- Constants ---
ASPECT_RATIO = 9 / 16 ASPECT_RATIO = 9 / 16
# Active per-channel profile (PLAN #1 v0). Populated from --channel / the
# CHANNEL_PROFILE env var in __main__; None when the job runs channel-less.
# Nothing reads it for generation yet -- later items (#3/#4/#6) will.
ACTIVE_PROFILE = None
# Load the YOLO model once (Keep for backup or scene analysis if needed) # Load the YOLO model once (Keep for backup or scene analysis if needed)
# YOLO_MODEL_PATH lets deployments point at a pre-downloaded weights file so a # YOLO_MODEL_PATH lets deployments point at a pre-downloaded weights file so a
# volume mounted over the workdir doesn't trigger a re-download at startup. # volume mounted over the workdir doesn't trigger a re-download at startup.
@ -1300,30 +1310,55 @@ def auto_hook_clip(clip_path, clip, captions=None):
def render_clip(input_video, final_output_video, output_format="auto", def render_clip(input_video, final_output_video, output_format="auto",
force_strategy=None, crop_overrides=None): force_strategy=None, crop_overrides=None, word_times=None):
"""Route a cut clip through the right renderer for the chosen output format. """Route a cut clip through the right renderer for the chosen output format.
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep. vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep.
``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the ``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the
clip editor's whole-clip framing override. ``crop_overrides`` positions clip editor's whole-clip framing override. ``crop_overrides`` positions
individual scenes by hand (the per-scene reframing editor) and wins over individual scenes by hand (the per-scene reframing editor) and wins over
``force_strategy`` for the scenes it names.""" ``force_strategy`` for the scenes it names. ``word_times`` are optional
clip-relative word onsets (seconds, clip start = 0) that steer punch-ins."""
if output_format == "horizontal": if output_format == "horizontal":
return finalize_clip_passthrough(input_video, final_output_video) return finalize_clip_passthrough(input_video, final_output_video)
aspect = 1.0 if output_format == "square" else ASPECT_RATIO aspect = 1.0 if output_format == "square" else ASPECT_RATIO
return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect, return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect,
force_strategy=force_strategy, force_strategy=force_strategy,
crop_overrides=crop_overrides) crop_overrides=crop_overrides,
word_times=word_times)
def clip_word_onsets(transcript, clip_start, clip_end):
"""Clip-relative onset seconds for the words spoken inside a clip.
The punch-in path wants "when a word started" on the cut clip's timeline
(0 = ``clip_start``). A word that straddles a boundary still contributes:
one already underway when the clip opens lands at 0, one crossing the end
lands at the clip's duration. Returns [] when the transcript has no word
timings, which leaves the audio envelope as the only beat source.
"""
if not transcript or clip_end <= clip_start:
return []
span = clip_end - clip_start
onsets = []
for seg in transcript.get("segments", []) or []:
for word in seg.get("words") or []:
if word.get("end", 0) <= clip_start or word.get("start", 0) >= clip_end:
continue
onset = word.get("start", 0) - clip_start
onsets.append(round(min(max(onset, 0.0), span), 3))
return sorted(onsets)
def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO, def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPECT_RATIO,
force_strategy=None, crop_overrides=None): force_strategy=None, crop_overrides=None, word_times=None):
""" """
Core logic to reframe a horizontal video to a target aspect ratio using Core logic to reframe a horizontal video to a target aspect ratio using
scene detection and Active Speaker Tracking (MediaPipe). scene detection and Active Speaker Tracking (MediaPipe).
aspect_ratio: width/height of the output (9/16 vertical, 1.0 square). aspect_ratio: width/height of the output (9/16 vertical, 1.0 square).
force_strategy / crop_overrides pin layouts and scene crops by hand (v2 force_strategy / crop_overrides pin layouts and scene crops by hand (v2
engine only — the v1 loop below has no layout concept beyond its own engine only — the v1 loop below has no layout concept beyond its own
classifier). classifier). word_times feeds clip-relative word onsets to the punch-in
beats (v2 only; the v1 loop has no punch-ins).
""" """
# v2 engine: analyze downscaled, render natively in ffmpeg. Any failure # v2 engine: analyze downscaled, render natively in ffmpeg. Any failure
# falls back to the v1 frame loop below so a v2 edge case can't kill jobs. # falls back to the v1 frame loop below so a v2 edge case can't kill jobs.
@ -1333,7 +1368,8 @@ def process_video_to_vertical(input_video, final_output_video, aspect_ratio=ASPE
t0 = time.time() t0 = time.time()
result = reframe_v2.render(input_video, final_output_video, aspect_ratio, result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
force_strategy=force_strategy, force_strategy=force_strategy,
crop_overrides=crop_overrides) crop_overrides=crop_overrides,
word_times=word_times)
print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s") print(f" ⏱️ Reframe v2 total: {time.time() - t0:.1f}s")
return result return result
except Exception as e: except Exception as e:
@ -1593,6 +1629,93 @@ def clear_transcript_checkpoint(output_dir):
print(f"⚠️ Could not remove transcript checkpoint: {e}") print(f"⚠️ Could not remove transcript checkpoint: {e}")
# The only handoff manifest schema this build understands (cadence PLAN #8).
HANDOFF_SCHEMA = "clipwright.handoff/1"
# The master's measured duration may differ from the manifest's edited timeline
# by this fraction before we refuse to align the edited-timeline transcript.
HANDOFF_DURATION_TOLERANCE = 0.01
class HandoffError(Exception):
"""A cadence handoff manifest is missing, invalid or does not match the master."""
def load_handoff_transcript(manifest_path, input_video, duration):
"""Load the cadence-edited transcript a handoff manifest points at.
Cadence emits word tokens with a leading space and compound fragments
without one (cadence PLAN #8, design rule #1), so every segment's words are
run through ``merge_continuation_words`` on load. Missing ``words`` lists
are left alone.
The manifest's ``edited.master`` is null in v1: the video passed via ``-i``
/ ``-u`` *is* the master, so its measured ``duration`` must match
``edited.duration`` within +/-1% or the edited-timeline alignment is not
trustworthy. ``sources[].path`` is never opened: those are emitter-local
paths (never honor a remote manifest's file references).
Raises ``HandoffError`` on any problem; the caller decides whether to refuse
the job.
"""
manifest_path = os.path.abspath(manifest_path)
try:
with open(manifest_path, encoding="utf-8") as f:
manifest = json.load(f)
except FileNotFoundError:
raise HandoffError(f"handoff manifest not found: {manifest_path}")
except json.JSONDecodeError as e:
raise HandoffError(f"malformed handoff manifest {manifest_path}: {e}")
except OSError as e:
raise HandoffError(f"could not read handoff manifest {manifest_path}: {e}")
if not isinstance(manifest, dict):
raise HandoffError(f"handoff manifest {manifest_path} must be a JSON object")
schema = manifest.get("schema")
if schema and schema != HANDOFF_SCHEMA:
raise HandoffError(
f"unsupported handoff schema {schema!r} (expected {HANDOFF_SCHEMA!r})")
# Duration gate: -i/-u is the edited master, so it has to match the manifest.
edited = manifest.get("edited") or {}
edited_duration = edited.get("duration") if isinstance(edited, dict) else None
if edited_duration is not None:
try:
edited_duration = float(edited_duration)
except (TypeError, ValueError):
raise HandoffError(
f"edited.duration must be a number, got {edited_duration!r}")
if duration and abs(float(duration) - edited_duration) > \
HANDOFF_DURATION_TOLERANCE * edited_duration:
raise HandoffError(
f"input duration {float(duration):.2f}s for "
f"{os.path.basename(str(input_video))} differs from the handoff's "
f"edited timeline {edited_duration:.2f}s by more than 1% — refusing "
f"the handoff. Pass --transcript explicitly if you need to force it.")
# transcript.path is resolved relative to the MANIFEST's directory.
transcript_ref = manifest.get("transcript")
if not isinstance(transcript_ref, dict) or not transcript_ref.get("path"):
raise HandoffError("handoff manifest has no transcript.path")
transcript_path = os.path.normpath(os.path.join(
os.path.dirname(manifest_path), str(transcript_ref["path"])))
try:
with open(transcript_path, encoding="utf-8") as f:
transcript = json.load(f)
except FileNotFoundError:
raise HandoffError(f"handoff transcript not found: {transcript_path}")
except json.JSONDecodeError as e:
raise HandoffError(f"malformed handoff transcript {transcript_path}: {e}")
except OSError as e:
raise HandoffError(f"could not read handoff transcript {transcript_path}: {e}")
if not isinstance(transcript, dict) or not transcript.get("segments"):
raise HandoffError(f"handoff transcript {transcript_path} has no segments")
for segment in transcript["segments"]:
if isinstance(segment, dict) and isinstance(segment.get("words"), list):
segment["words"] = merge_continuation_words(segment["words"])
return transcript
CLIP_RETRY_PAUSE_SECONDS = float(os.environ.get("CLIP_RETRY_PAUSE_SECONDS", "10")) CLIP_RETRY_PAUSE_SECONDS = float(os.environ.get("CLIP_RETRY_PAUSE_SECONDS", "10"))
@ -1607,6 +1730,57 @@ def clip_render_order(shorts):
return sorted(range(len(shorts)), key=lambda i: (-score(i), i)) return sorted(range(len(shorts)), key=lambda i: (-score(i), i))
# --- Retention provenance (PLAN #10, "instrument now") ---------------------
# Every clip carries one versioned provenance object so a future retention /
# analytics loop becomes a data pull instead of a re-architecture. It records
# only what the pipeline already produced: the active profile, the model's
# predicted score, how the start boundary was chosen (#2a hook-first vs the
# plain word snap), whether a long-form bridge target was attached (#6), and
# the publish target. Additive: no existing metadata field changes shape. The
# loop itself is deliberately NOT built here.
PROVENANCE_SCHEMA_VERSION = 1
def build_provenance(clip, profile=None):
"""The versioned provenance record for one clip (PLAN #10).
Reads the ``hook_first`` block #2a writes when it moves a clip start, the
merged #6 bridge fields, the model's ``predicted_score`` and the active
profile. Anything the pipeline does not have at clip time (e.g. a
title-validator version or a chosen thumbnail role) is omitted rather than
guessed. Pure and side-effect free so it can be unit tested without a
render.
"""
clip = clip if isinstance(clip, dict) else {}
hook_first = clip.get("hook_first")
hook_first = hook_first if isinstance(hook_first, dict) else None
applied = hook_first is not None
related = (clip.get("related_video_url") or "")
related = related.strip() if isinstance(related, str) else ""
return {
"schema_version": PROVENANCE_SCHEMA_VERSION,
"profile": getattr(profile, "slug", None) or None,
"predicted_score": clip.get("predicted_score"),
"hook": {
"applied": applied,
# Which pass set the final start: the deterministic hook-first trim
# (#2a), or the plain word-boundary snap it ran on top of.
"source": "hook_first" if applied else "snap",
"start": hook_first.get("start") if applied else None,
"trim": hook_first.get("trim") if applied else None,
"proposed": hook_first.get("proposed") if applied else None,
},
"bridge": {
"present": bool(related),
"related_video_url": related or None,
},
"publish": {
"postiz_integration_id": getattr(
profile, "default_postiz_integration_id", None),
},
}
def _free_gpu_cache(): def _free_gpu_cache():
try: try:
import torch import torch
@ -1765,6 +1939,11 @@ def get_viral_clips(transcript_result, video_duration):
model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite' model_name = os.environ.get("GEMINI_MODEL") or 'gemini-3.1-flash-lite'
print(f"\U0001f916 Model: {model_name} | language: {language}") print(f"\U0001f916 Model: {model_name} | language: {language}")
# PLAN #1: the active channel profile tunes the copy fields (Short title,
# viral hook). ACTIVE_PROFILE is set once at CLI startup; None here renders
# an empty block, leaving the prompt byte-identical to a profile-less run.
profile_rules = profile_prompts.clip_rules_block(ACTIVE_PROFILE)
# Full word list — ground truth for snapping cut points. # Full word list — ground truth for snapping cut points.
words = [] words = []
for segment in transcript_result['segments']: for segment in transcript_result['segments']:
@ -1829,6 +2008,7 @@ def get_viral_clips(transcript_result, video_duration):
video_duration=video_duration, language=language, video_duration=video_duration, language=language,
min_clips=lo, max_clips=hi, min_clips=lo, max_clips=hi,
min_secs=min_secs, max_secs=max_secs, min_secs=min_secs, max_secs=max_secs,
profile_rules=profile_rules,
windows_json=json.dumps(_payload(ws), ensure_ascii=False)) windows_json=json.dumps(_payload(ws), ensure_ascii=False))
return build return build
@ -1875,6 +2055,30 @@ def get_viral_clips(transcript_result, video_duration):
ns, ne = snap_clip_to_words(s.get("start", 0), s.get("end", 0), words, video_duration, ns, ne = snap_clip_to_words(s.get("start", 0), s.get("end", 0), words, video_duration,
min_duration=min_secs, max_duration=max_secs) min_duration=min_secs, max_duration=max_secs)
s["start"], s["end"] = ns, ne s["start"], s["end"] = ns, ne
# Hook-first boundaries (#2a): move each snapped start onto the first
# strong spoken hook, trimming wind-up so the clip opens on the hook.
# Deterministic and word-based (no LLM); a clip with no clear hook is
# left exactly where the snap put it. The pass is env-capped and on by
# default (HOOK_FIRST); see clip_selection.find_hook_start.
if hook_first_enabled():
moved = 0
for s in shorts:
old_start = float(s.get("start", 0) or 0)
new_start = find_hook_start(words, old_start, s.get("end", 0),
min_duration=min_secs)
if new_start is None or new_start >= old_start:
continue
trim = round(old_start - new_start, 3)
print(f" Hook-first clip {s.get('source_window_id') or '?'}: "
f"start {old_start:.2f} -> {new_start:.2f} (trim {trim:.2f}s)")
s["start"] = new_start
s["hook_first"] = {"start": new_start, "trim": trim,
"proposed": old_start}
moved += 1
if moved:
print(f" Hook-first trimmed {moved} of {len(shorts)} clip start(s).")
deduped = dedupe_overlapping(shorts) deduped = dedupe_overlapping(shorts)
if len(deduped) < len(shorts): if len(deduped) < len(shorts):
print(f" Dropped {len(shorts) - len(deduped)} clip(s) overlapping a " print(f" Dropped {len(shorts) - len(deduped)} clip(s) overlapping a "
@ -2032,10 +2236,46 @@ if __name__ == '__main__':
help="Output aspect: vertical/auto (9:16), horizontal (keep 16:9), square (1:1).") help="Output aspect: vertical/auto (9:16), horizontal (keep 16:9), square (1:1).")
parser.add_argument('--transcript', type=str, parser.add_argument('--transcript', type=str,
help="Path to a precomputed transcript JSON (transcribe_media shape); skips transcription.") help="Path to a precomputed transcript JSON (transcribe_media shape); skips transcription.")
parser.add_argument('--handoff', type=str, default=None,
help="Path to a cadence handoff manifest JSON. Loads the "
"edited-timeline transcript it points at (relative to "
"the manifest), validates the master duration and "
"skips transcription.")
parser.add_argument('--channel', type=str, default=None,
help="Channel profile slug (channels/<slug>.json); "
"overrides the CHANNEL_PROFILE env var.")
parser.add_argument('--longform-url', type=str, default=None,
help="Target long-form video URL for the Shorts->long-form "
"bridge copy/checklist (PLAN #6). Optional: without it "
"the active profile's published_video_history is used.")
args = parser.parse_args() args = parser.parse_args()
output_format = args.format output_format = args.format
# Per-channel profile (PLAN #1 v0): resolve and validate before any work so
# a bad profile fails at startup, and hang it off a module global that later
# items (#3/#4/#6) will read. The API passes CHANNEL_PROFILE; --channel wins
# for local CLI runs. Generation behaviour is deliberately untouched.
_channel_slug = args.channel or os.environ.get("CHANNEL_PROFILE") or None
if _channel_slug:
try:
ACTIVE_PROFILE = load_profile(_channel_slug)
print(f"📦 Channel profile: {_channel_slug} "
f"(tone={ACTIVE_PROFILE.tone or 'unset'})")
except ProfileError as e:
if args.channel:
# An explicit --channel that does not load is a config error.
print(f"❌ Channel profile {args.channel!r}: {e}")
sys.exit(1)
# Env-derived only: warn and keep the run identical to channel-less.
print(f"⚠️ Ignoring CHANNEL_PROFILE={_channel_slug!r}: {e}")
# Shorts -> long-form bridge target (PLAN #6). Explicit --longform-url wins;
# otherwise the per-clip generator falls back to the profile history.
longform_url = (args.longform_url or os.environ.get("LONGFORM_URL") or "").strip() or None
if longform_url:
print(f"🔗 Bridge target (long-form): {longform_url}")
script_start_time = time.time() script_start_time = time.time()
def _ensure_dir(path: str) -> str: def _ensure_dir(path: str) -> str:
@ -2093,7 +2333,7 @@ if __name__ == '__main__':
threading.Thread(target=_early_work, args=(audio_path, audio_duration), threading.Thread(target=_early_work, args=(audio_path, audio_duration),
daemon=True).start() daemon=True).start()
use_early = (not args.skip_analysis and not args.transcript use_early = (not args.skip_analysis and not args.transcript and not args.handoff
and os.environ.get("EARLY_AUDIO", "1").strip() != "0" and os.environ.get("EARLY_AUDIO", "1").strip() != "0"
and not os.environ.get("MAX_SOURCE_MINUTES", "").strip() and not os.environ.get("MAX_SOURCE_MINUTES", "").strip()
and not os.path.exists(os.path.join(output_dir, TRANSCRIPT_CHECKPOINT))) and not os.path.exists(os.path.join(output_dir, TRANSCRIPT_CHECKPOINT)))
@ -2184,10 +2424,23 @@ if __name__ == '__main__':
# to Gemini vision (picks clips from the imagery instead of the speech). # to Gemini vision (picks clips from the imagery instead of the speech).
from clipwright.pipeline.transcribe_backends import NoAudioError from clipwright.pipeline.transcribe_backends import NoAudioError
transcript = None transcript = None
# Cadence handoff (PLAN #8): the edited-timeline transcript, already
# aligned to the master, so there is nothing to transcribe. It wins over
# --transcript. A handoff that fails validation is refused (not silently
# re-transcribed): the whole point is alignment to the edited timeline,
# and guessing would cut clips on the wrong one.
if args.handoff:
try:
transcript = load_handoff_transcript(args.handoff, input_video, duration)
print(f"⏩ Using cadence handoff transcript "
f"({len(transcript['segments'])} segments) — skipping transcription.")
except HandoffError as e:
print(f"❌ Handoff refused: {e}")
sys.exit(1)
# Module handover (issue #68): another module already transcribed this # Module handover (issue #68): another module already transcribed this
# exact source with the same backend, so reuse its output. Any problem # exact source with the same backend, so reuse its output. Any problem
# with the file falls back to transcribing normally rather than failing. # with the file falls back to transcribing normally rather than failing.
if args.transcript: elif args.transcript:
try: try:
with open(args.transcript, 'r') as f: with open(args.transcript, 'r') as f:
transcript = json.load(f) transcript = json.load(f)
@ -2250,6 +2503,19 @@ if __name__ == '__main__':
else: else:
print(f"🔥 Found {len(clips_data['shorts'])} clips!") print(f"🔥 Found {len(clips_data['shorts'])} clips!")
# Shorts -> long-form bridge copy (PLAN #6): per clip, derive the
# description block, first-comment text, target URL and the manual
# Studio checklist from the active profile. The explicit
# --longform-url wins over the profile's published_video_history.
# The related-video link and comment pinning are Studio-UI only
# (no API), hence the checklist rather than a server-side action.
for _clip in clips_data['shorts']:
_clip.update(bridge.build_bridge(
ACTIVE_PROFILE, clip=_clip, related_video_url=longform_url))
# Retention provenance (PLAN #10): one versioned record per
# clip, written with the metadata below. Additive only.
_clip['provenance'] = build_provenance(_clip, ACTIVE_PROFILE)
# Save metadata. Silent videos have no transcript → no subtitles, # Save metadata. Silent videos have no transcript → no subtitles,
# which is correct (there's no speech to caption). # which is correct (there's no speech to caption).
clips_data['transcript'] = transcript or {"language": "none", "segments": []} clips_data['transcript'] = transcript or {"language": "none", "segments": []}
@ -2285,7 +2551,12 @@ if __name__ == '__main__':
# is a derived hooked_ file, and captions go last on top of # is a derived hooked_ file, and captions go last on top of
# whichever is current. Each worker writes only its own clip # whichever is current. Each worker writes only its own clip
# dict, so the re-dump after the pool is race-free. # dict, so the re-dump after the pool is race-free.
success = render_clip(clip_temp_path, clip_final_path, output_format) # Spoken emphasis drives punch-in timing when the source
# transcript carries word timestamps; [] falls back to the
# audio envelope inside the renderer.
word_times = clip_word_onsets(transcript, start, end)
success = render_clip(clip_temp_path, clip_final_path, output_format,
word_times=word_times)
if success: if success:
print(f" 🎞️ Clip {i+1} framed") print(f" 🎞️ Clip {i+1} framed")
deliver_path = clip_final_path deliver_path = clip_final_path

View file

@ -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)

View file

@ -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 ``<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

View file

@ -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())

View file

@ -673,6 +673,9 @@ function App() {
auto_hook_style: data.autoHook ? (data.autoHookStyle || 'pill') : null, auto_hook_style: data.autoHook ? (data.autoHookStyle || 'pill') : null,
// 'auto' is the server default, so only a deliberate choice travels. // 'auto' is the server default, so only a deliberate choice travels.
layouts: data.layout && data.layout !== 'auto' ? data.layout : null, layouts: data.layout && data.layout !== 'auto' ? data.layout : null,
// Channel profile slug (channels/<slug>.json). Absent = no profile, so
// the default request stays byte-identical to the pre-feature one.
channel: data.channel || null,
}; };
if (data.type === 'url') { if (data.type === 'url') {

View file

@ -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 (
<Modal
isOpen={isOpen}
onClose={onClose}
eyebrow="YOUTUBE · BRIDGE"
title="shorts → long-form"
size="lg"
>
{loading && (
<div className="flex items-center justify-center gap-2 py-10 text-sm text-muted lowercase">
<Loader2 size={16} className="animate-spin text-brass" /> loading bridge…
</div>
)}
{!loading && error && (
<div className="px-3 py-2 rounded-input text-xs text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)] flex items-start gap-2">
<AlertCircle size={14} className="mt-0.5 shrink-0" />
<span className="break-words">{error}</span>
</div>
)}
{!loading && !error && data && (
<div>
<p className="text-xs text-muted leading-snug mb-5">
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.
</p>
{/* Related-video target */}
<section className="mb-5">
<label className="eyebrow block mb-1.5">RELATED VIDEO TARGET</label>
{data.related_video_url ? (
<div className="flex items-center gap-2 bg-paper rounded-input border border-rule px-3 py-2 min-w-0">
<Youtube size={14} className="text-muted shrink-0" />
<a
href={data.related_video_url}
target="_blank"
rel="noopener noreferrer"
className="text-xs text-ink2 truncate flex-1 min-w-0 hover:text-brass transition-colors"
>
{data.related_video_url}
</a>
<button
onClick={() => handleCopy('target', data.related_video_url)}
aria-label="copy related video url"
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
>
{copied === 'target' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
</button>
</div>
) : (
<div className="px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
<AlertCircle size={14} className="mt-0.5 shrink-0" />
<span>
No related video set for this clip yet. Paste the long-form URL into YouTube Studio's
{' '}<b className="font-medium">Related video</b> field when you set it up — the checklist below has the steps.
</span>
</div>
)}
</section>
{/* Manual Studio checklist */}
<section className="mb-5">
<div className="flex items-center justify-between gap-2 mb-2">
<label className="eyebrow">STUDIO CHECKLIST</label>
<span className="readout">manual · no api</span>
</div>
{Array.isArray(data.checklist) && data.checklist.length > 0 ? (
<ol className="space-y-1.5">
{data.checklist.map((step, i) => {
const done = !!checkedSteps[i];
return (
<li key={i}>
<button
type="button"
onClick={() => toggleStep(i)}
aria-pressed={done}
className={`w-full text-left flex items-start gap-2.5 px-3 py-2 rounded-input border transition-colors ${done ? 'border-rule bg-paper opacity-70' : 'border-rule hover:bg-paper3'}`}
>
{done
? <CheckCircle2 size={15} className="text-ok mt-0.5 shrink-0" />
: <span className="mt-0.5 w-[15px] h-[15px] rounded-full border border-rule2 shrink-0" aria-hidden="true" />}
<span className={`text-xs leading-snug ${done ? 'text-muted' : 'text-ink2'}`}>{step}</span>
</button>
</li>
);
})}
</ol>
) : (
<p className="text-xs text-muted lowercase">no checklist saved for this clip.</p>
)}
</section>
{/* Copy-paste copy */}
<section className="mb-5">
<div className="flex items-center justify-between gap-2 mb-1.5">
<label className="eyebrow">DESCRIPTION BRIDGE</label>
<button
onClick={() => handleCopy('desc', data.description_bridge)}
aria-label="copy description bridge"
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
>
{copied === 'desc' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
</button>
</div>
{data.description_bridge ? (
<p className="text-xs text-ink2 select-all break-words whitespace-pre-wrap bg-paper rounded-input p-3 border border-rule max-h-40 overflow-y-auto custom-scrollbar">
{data.description_bridge}
</p>
) : (
<p className="text-xs text-muted lowercase bg-paper rounded-input p-3 border border-dashed border-rule">
no description copy generated for this clip.
</p>
)}
</section>
<section className="mb-5">
<div className="flex items-center justify-between gap-2 mb-1.5">
<label className="eyebrow">FIRST COMMENT</label>
<button
onClick={() => handleCopy('comment', data.first_comment)}
aria-label="copy first comment"
className="p-1 rounded-full text-muted hover:text-brass transition-colors shrink-0"
>
{copied === 'comment' ? <Check size={14} className="text-ok" /> : <Copy size={14} />}
</button>
</div>
{data.first_comment ? (
<p className="text-xs text-ink2 select-all break-words whitespace-pre-wrap bg-paper rounded-input p-3 border border-rule">
{data.first_comment}
</p>
) : (
<p className="text-xs text-muted lowercase bg-paper rounded-input p-3 border border-dashed border-rule">
no first comment generated for this clip.
</p>
)}
</section>
{/* Optional opt-in comment posting */}
<section className="border-t border-rule pt-4">
<div className="flex items-center gap-2 mb-1.5">
<label className="eyebrow">POST FIRST COMMENT</label>
<span className="badge-ok">opt-in</span>
</div>
<p className="text-xs text-muted leading-snug mb-3">
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.
</p>
{!configured ? (
<div className="px-3 py-2 rounded-input text-xs text-warn bg-[color-mix(in_oklab,var(--color-warn)_10%,transparent)] flex items-start gap-2">
<AlertCircle size={14} className="mt-0.5 shrink-0" />
<span>
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.
</span>
</div>
) : (
<div className="space-y-2">
<div className="flex flex-col sm:flex-row gap-2">
<input
type="text"
value={videoId}
onChange={(e) => 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"
/>
<button
onClick={handlePostComment}
disabled={posting || !canPostComment}
className="btn-primary shrink-0"
title={!data.first_comment ? 'No comment text to post' : (videoId.trim() ? undefined : 'Enter the published Short id first')}
>
{posting
? <><Loader2 size={15} className="animate-spin" /> posting…</>
: <><MessageSquare size={15} /> post comment</>}
</button>
</div>
{postStatus && (
<div className={`px-3 py-2 rounded-input text-xs flex items-start gap-2 ${postStatus.ok
? 'text-ok bg-[color-mix(in_oklab,var(--color-ok)_10%,transparent)]'
: 'text-danger bg-[color-mix(in_oklab,var(--color-danger)_10%,transparent)]'}`}
>
{postStatus.ok
? <Check size={14} className="mt-0.5 shrink-0" />
: <AlertCircle size={14} className="mt-0.5 shrink-0" />}
<span className="break-words">{postStatus.msg}</span>
</div>
)}
</div>
)}
<p className="readout mt-3 flex items-center gap-1.5">
<Link2 size={12} className="shrink-0" /> related-video link + pin: Studio only
</p>
</section>
</div>
)}
</Modal>
);
}

View file

@ -61,6 +61,13 @@ export default function MediaInput({ onProcess, isProcessing }) {
const [layout, setLayout] = useState(() => { const [layout, setLayout] = useState(() => {
try { return localStorage.getItem('cw_layout') || 'auto'; } catch { return 'auto'; } try { return localStorage.getItem('cw_layout') || 'auto'; } catch { return 'auto'; }
}); });
// Channel profile (channels/<slug>.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); const infoRef = useRef(null);
// Close the compatibility popover on any outside click. // Close the compatibility popover on any outside click.
@ -99,6 +106,22 @@ export default function MediaInput({ onProcess, isProcessing }) {
.catch(() => {}); .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 // 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 // where they left off. Not auto-submitted — the rights attestation below
// has to be ticked by the user. // has to be ticked by the user.
@ -124,6 +147,9 @@ export default function MediaInput({ onProcess, isProcessing }) {
autoHook, autoHook,
autoHookStyle, autoHookStyle,
layout, 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 { try {
localStorage.setItem('cw_auto_hook', autoHook ? '1' : '0'); localStorage.setItem('cw_auto_hook', autoHook ? '1' : '0');
@ -291,6 +317,32 @@ export default function MediaInput({ onProcess, isProcessing }) {
</div> </div>
</div> </div>
{/* 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 && (
<div className="mt-5" data-tutorial="channel-profile">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="eyebrow">channel profile</p>
<select
value={channel}
onChange={(e) => setChannel(e.target.value)}
className="input-field !w-auto text-xs py-1.5"
aria-label="channel profile"
>
<option value="none">None (generic)</option>
{channels.map((ch) => (
<option key={ch.slug} value={ch.slug}>{ch.name || ch.slug}</option>
))}
</select>
</div>
<p className="text-[11px] leading-relaxed text-muted mt-1.5">
Tailors titles, hooks, description and thumbnail for that channel.
</p>
</div>
)}
{/* Advanced generation controls — collapsed by default; blank = AI decides */} {/* Advanced generation controls — collapsed by default; blank = AI decides */}
<div className="mt-4"> <div className="mt-4">
<button <button
@ -353,6 +405,7 @@ export default function MediaInput({ onProcess, isProcessing }) {
<option value="auto">Auto (AI picks per video)</option> <option value="auto">Auto (AI picks per video)</option>
<option value="split">Two speakers stacked</option> <option value="split">Two speakers stacked</option>
<option value="screencast">Screen over presenter</option> <option value="screencast">Screen over presenter</option>
<option value="code">Code / terminal (zoom to text)</option>
<option value="none">Single crop only</option> <option value="none">Single crop only</option>
</select> </select>
</div> </div>

View file

@ -4,6 +4,7 @@ import { getApiUrl } from '../config';
import { apiFetch } from '../lib/api'; import { apiFetch } from '../lib/api';
import SubtitleModal from './SubtitleModal'; import SubtitleModal from './SubtitleModal';
import HookModal from './HookModal'; import HookModal from './HookModal';
import BridgeModal from './BridgeModal';
import Modal from './ui/Modal'; import Modal from './ui/Modal';
import { renderInBrowser } from '../lib/renderInBrowser'; 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 [isSubtitling, setIsSubtitling] = useState(false);
const [isHooking, setIsHooking] = useState(false); const [isHooking, setIsHooking] = useState(false);
const [showHookModal, setShowHookModal] = useState(false); const [showHookModal, setShowHookModal] = useState(false);
const [showBridgeModal, setShowBridgeModal] = useState(false);
const [editError, setEditError] = useState(null); const [editError, setEditError] = useState(null);
const [clipDuration, setClipDuration] = useState(() => { const [clipDuration, setClipDuration] = useState(() => {
@ -924,6 +926,15 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
{isHooking ? 'saving…' : 'edit hook'} {isHooking ? 'saving…' : 'edit hook'}
</button> </button>
<button
onClick={() => setShowBridgeModal(true)}
className={QUIET_BTN}
title="Shorts → long-form bridge: related video, first comment, Studio checklist"
>
<Link2 size={16} className="text-muted group-hover:text-brass transition-colors shrink-0" />
bridge
</button>
<button <button
onClick={() => setShowModal(true)} onClick={() => setShowModal(true)}
className="btn-primary flex-col gap-1 py-2.5 sm:py-2 px-1 text-[11px] leading-none rounded-input whitespace-nowrap" className="btn-primary flex-col gap-1 py-2.5 sm:py-2 px-1 text-[11px] leading-none rounded-input whitespace-nowrap"
@ -1176,6 +1187,13 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g
onRemove={burnedHook ? handleRemoveHook : null} onRemove={burnedHook ? handleRemoveHook : null}
/> />
<BridgeModal
isOpen={showBridgeModal}
onClose={() => setShowBridgeModal(false)}
jobId={jobId}
clipIndex={index}
/>
</div> </div>
); );
} }

View file

@ -0,0 +1,99 @@
"""L1 API: cadence handoff upload + submit (PLAN #8).
The bundle rides the existing /api/uploads slot flow (``kind="handoff"``); the
test asserts the staged manifest/transcript land in the job dir and the queued
child command carries ``--handoff``. The worker never runs here.
"""
import io
import json
import os
import zipfile
import pytest
pytestmark = pytest.mark.e2e
KEY = {"X-Gemini-Key": "test-key"}
def _zip_bytes():
manifest = {
"schema": "clipwright.handoff/1",
"generator": {"name": "cadence", "version": "0.1.0"},
"edited": {"duration": 6.0, "master": None},
"sources": [{"index": 0, "path": "/emitter/local/rec.mkv"}],
"transcript": {"path": "rec.transcript.json"},
"candidates": [],
}
transcript = {
"text": " hello world",
"language": "en",
"segments": [{"start": 0.0, "end": 1.0, "text": " hello world",
"words": [{"word": " hello", "start": 0.0, "end": 0.4},
{"word": " world", "start": 0.4, "end": 1.0}]}],
}
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr("rec.handoff.json", json.dumps(manifest))
zf.writestr("rec.transcript.json", json.dumps(transcript))
return buf.getvalue()
async def _master_upload(client, media_factory):
reserved = await client.post("/api/uploads", json={"filename": "master.mp4"})
uid = reserved.json()["upload_id"]
assert (await client.put(f"/api/uploads/{uid}",
content=media_factory.six.read_bytes())).status_code == 200
return uid
async def _handoff_upload(client, payload):
reserved = await client.post("/api/uploads",
json={"filename": "bundle.zip", "kind": "handoff"})
assert reserved.status_code == 200
assert reserved.json()["kind"] == "handoff"
uid = reserved.json()["upload_id"]
put = await client.put(f"/api/uploads/{uid}", content=payload)
assert put.status_code == 200
assert put.json()["kind"] == "handoff"
return uid
async def test_handoff_id_stages_bundle_and_queues_the_flag(client, app_state, media_factory):
master_id = await _master_upload(client, media_factory)
handoff_id = await _handoff_upload(client, _zip_bytes())
resp = await client.post("/api/process", headers=KEY, json={
"upload_id": master_id, "handoff_id": handoff_id, "acknowledged": True})
assert resp.status_code == 200, resp.text
job = app_state.app.jobs[resp.json()["job_id"]]
assert "--handoff" in job["cmd"]
manifest_path = job["cmd"][job["cmd"].index("--handoff") + 1]
assert os.path.exists(manifest_path)
staged = json.loads(open(manifest_path, encoding="utf-8").read())
assert staged["transcript"]["path"] == "source_transcript.json"
assert os.path.exists(os.path.join(os.path.dirname(manifest_path),
"source_transcript.json"))
# The slot is consumed; the master upload still follows its own path.
assert handoff_id not in app_state.app.pending_uploads
async def test_non_zip_handoff_bundle_is_400(client, app_state, media_factory):
master_id = await _master_upload(client, media_factory)
handoff_id = await _handoff_upload(client, b"not a zip")
resp = await client.post("/api/process", headers=KEY, json={
"upload_id": master_id, "handoff_id": handoff_id, "acknowledged": True})
assert resp.status_code == 400
assert "ZIP" in resp.json()["detail"]
async def test_unknown_handoff_id_is_404(client, app_state, media_factory):
master_id = await _master_upload(client, media_factory)
resp = await client.post("/api/process", headers=KEY, json={
"upload_id": master_id, "handoff_id": "nope", "acknowledged": True})
assert resp.status_code == 404

View file

@ -486,6 +486,55 @@ async def test_describe_success(client, app_state, thumb_stubs, monkeypatch):
assert args[1] == "My Title" and args[2] == segments assert args[1] == "My Title" and args[2] == segments
# --------------------------------------------------------------------------- #
# Channel profiles reach the Studio generators (PLAN #1)
# --------------------------------------------------------------------------- #
async def test_analyze_passes_the_channel_profile(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post(
"/api/thumbnail/analyze",
data={"channel": "cseea"},
files={"file": ("v.mp4", b"video", "video/mp4")})
assert resp.status_code == 200, resp.text
_, kwargs = thumb_stubs.calls.analyze[0]
assert kwargs["profile"].slug == "cseea"
async def test_generate_passes_the_channel_profile(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
resp = await client.post(
"/api/thumbnail/generate",
data={"session_id": "g1", "title": "T", "channel": "pedro"})
assert resp.status_code == 200, resp.text
_, kwargs = thumb_stubs.calls.generate[0]
assert kwargs["profile"].slug == "pedro"
async def test_describe_passes_the_channel_profile(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["d1"] = {
"transcript_segments": [{"start": 0.0, "end": 5.0, "text": "hello"}],
"language": "en", "video_duration": 5.0}
resp = await client.post("/api/thumbnail/describe",
json={"session_id": "d1", "title": "T", "channel": "cseea"})
assert resp.status_code == 200, resp.text
_, kwargs = thumb_stubs.calls.describe[0]
assert kwargs["profile"].slug == "cseea"
async def test_unknown_channel_is_400(client, app_state, thumb_stubs, monkeypatch):
monkeypatch.setenv("GEMINI_API_KEY", "k")
app_state.app.thumbnail_sessions["d1"] = {
"transcript_segments": [{"start": 0.0, "end": 5.0, "text": "hello"}],
"language": "en", "video_duration": 5.0}
resp = await client.post("/api/thumbnail/describe",
json={"session_id": "d1", "title": "T", "channel": "nope"})
assert resp.status_code == 400
assert "Invalid channel profile" in resp.json()["detail"]
assert thumb_stubs.calls.describe == []
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
# POST /api/thumbnail/publish + GET status # POST /api/thumbnail/publish + GET status
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #

View file

@ -0,0 +1,102 @@
"""L4 — cadence handoff CLI (PLAN #8).
Runs the REAL ``python -m clipwright.pipeline.main`` with real ffmpeg and the
stub_env ASR/Gemini. Proves a valid handoff skips ASR (the metadata transcript
is the handoff's, not the canned stub's) and that a bad handoff is refused.
"""
import json
import pytest
pytestmark = [pytest.mark.e2e, pytest.mark.pipeline]
# 12 tokens in ``text`` so main.speech_is_sparse does not fall back to vision.
HANDOFF_TEXT = "This handoff transcript proves the ASR step was skipped entirely -ish here"
HANDOFF_WORDS = [
{"word": " This", "start": 0.0, "end": 0.3},
{"word": " handoff", "start": 0.3, "end": 0.7},
{"word": " transcript", "start": 0.7, "end": 1.2},
{"word": " proves", "start": 1.2, "end": 1.6},
{"word": " the", "start": 1.6, "end": 1.8},
{"word": " ASR", "start": 1.8, "end": 2.2},
{"word": " step", "start": 2.2, "end": 2.6},
{"word": " was", "start": 2.6, "end": 2.9},
{"word": " skipped", "start": 2.9, "end": 3.4},
{"word": " entirely", "start": 3.4, "end": 4.0},
{"word": "-ish", "start": 4.0, "end": 4.3}, # fragment: no leading space
{"word": " here", "start": 4.3, "end": 4.8},
]
def _write_bundle(tmp_path, *, edited_duration=6.0, transcript_name="rec.transcript.json",
write_transcript=True, transcript_ref="rec.transcript.json"):
transcript = {
"text": HANDOFF_TEXT,
"language": "en",
"segments": [{"start": 0.0, "end": 4.8, "text": HANDOFF_TEXT,
"words": HANDOFF_WORDS}],
}
if write_transcript:
(tmp_path / transcript_name).write_text(json.dumps(transcript), encoding="utf-8")
manifest = {
"schema": "clipwright.handoff/1",
"generator": {"name": "cadence", "version": "0.1.0"},
"edited": {"timeline": "voice-audio", "duration": edited_duration, "master": None},
"sources": [{"index": 0, "path": "/emitter/local/never-open.mkv"}],
"transcript": {"path": transcript_ref},
"candidates": [],
"chapters": [],
}
manifest_path = tmp_path / "rec.handoff.json"
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
return manifest_path
def _metadata(out):
files = list(out.glob("*_metadata.json"))
assert len(files) == 1
return json.loads(files[0].read_text())
def test_handoff_skips_asr_and_merges_words(run_pipeline, pipeline_env, media_factory, tmp_path):
pipeline_env["AUTO_LAYOUT"] = "0"
pipeline_env["FFMPEG_ENCODER"] = "x264"
manifest = _write_bundle(tmp_path)
out = tmp_path / "out"
result = run_pipeline(media_factory.six, "-o", str(out), "--handoff", str(manifest))
assert result.returncode == 0, (
f"CLI failed ({result.returncode})\nSTDOUT:\n{result.stdout[-4000:]}\n"
f"STDERR:\n{result.stderr[-4000:]}")
meta = _metadata(out)
words = meta["transcript"]["segments"][0]["words"]
# The handoff's words (not the canned ASR stub's) and the fragment merged.
assert any(w["word"] == " entirely-ish" for w in words)
assert all("canned" not in w["word"] for w in words)
assert list(out.glob("*_clip_*.mp4"))
def test_handoff_duration_mismatch_is_refused(run_pipeline, pipeline_env, media_factory, tmp_path):
pipeline_env["AUTO_LAYOUT"] = "0"
manifest = _write_bundle(tmp_path, edited_duration=60.0)
out = tmp_path / "out"
result = run_pipeline(media_factory.six, "-o", str(out), "--handoff", str(manifest))
assert result.returncode != 0
assert "refusing the handoff" in result.stdout
assert "--transcript" in result.stdout
assert not list(out.glob("*_metadata.json"))
def test_handoff_missing_transcript_is_refused(run_pipeline, pipeline_env, media_factory, tmp_path):
pipeline_env["AUTO_LAYOUT"] = "0"
manifest = _write_bundle(tmp_path, write_transcript=False)
out = tmp_path / "out"
result = run_pipeline(media_factory.six, "-o", str(out), "--handoff", str(manifest))
assert result.returncode != 0
assert "transcript not found" in result.stdout
assert not list(out.glob("*_metadata.json"))

View file

@ -14,6 +14,9 @@ import pytest
from clipwright.layouts import layout_ranges from clipwright.layouts import layout_ranges
from clipwright.layouts import layout_picker 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 punch_in
from clipwright.layouts import screencast_layout from clipwright.layouts import screencast_layout
from clipwright.layouts import split_layout from clipwright.layouts import split_layout
@ -26,6 +29,7 @@ VERTICAL = 9 / 16
_FAKE_LAYOUT_MODULES = { _FAKE_LAYOUT_MODULES = {
"split_layout": "clipwright.layouts.split_layout", "split_layout": "clipwright.layouts.split_layout",
"screencast_layout": "clipwright.layouts.screencast_layout", "screencast_layout": "clipwright.layouts.screencast_layout",
"code_layout": "clipwright.layouts.code_layout",
"active_speaker": "clipwright.layouts.active_speaker", "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.screencast_layout"].ENABLED is True
assert mods["clipwright.layouts.split_layout"].ENABLED is False 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): def test_none_is_inert(self, monkeypatch):
mods = fake_modules(monkeypatch) mods = fake_modules(monkeypatch)
assert layout_picker.apply("none") == [] assert layout_picker.apply("none") == []
@ -104,6 +117,7 @@ class TestApiLayoutEnv:
def test_explicit_picks_map_to_their_env_vars(self, layout_env): def test_explicit_picks_map_to_their_env_vars(self, layout_env):
assert layout_env(["split"])["SPLIT_LAYOUT"] == "1" assert layout_env(["split"])["SPLIT_LAYOUT"] == "1"
assert layout_env(["screencast"])["SCREENCAST_LAYOUT"] == "1" assert layout_env(["screencast"])["SCREENCAST_LAYOUT"] == "1"
assert layout_env(["code"])["CODE_LAYOUT"] == "1"
assert layout_env(["punch_in"])["PUNCH_IN"] == "1" assert layout_env(["punch_in"])["PUNCH_IN"] == "1"
def test_split_implies_the_speaker_signal(self, layout_env): 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}]) got = layout_ranges.remap(ranges, [{"start": 5, "end": 12}])
assert got == [{"start": 0.0, "end": 5.0, "layout": "split"}, assert got == [{"start": 0.0, "end": 5.0, "layout": "split"},
{"start": 5.0, "end": 7.0, "layout": "track"}] {"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())

View file

@ -164,7 +164,9 @@ class TestConcepts:
assert len(out) == 3 assert len(out) == 3
assert out[0]["text"] == "ESTO FUNCIONA" assert out[0]["text"] == "ESTO FUNCIONA"
assert out[0]["text_position"] == "left" 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): def test_plan_thumbnail_concepts_parses_the_client_json(self):
concepts = thumbnail.plan_thumbnail_concepts(_FakeClient(), "A title", 2) concepts = thumbnail.plan_thumbnail_concepts(_FakeClient(), "A title", 2)

101
tests/test_bridge.py Normal file
View file

@ -0,0 +1,101 @@
"""Shorts -> long-form bridge copy (PLAN #6): pure, deterministic generation.
The bridge is derived from the active profile (+ its ``published_video_history``)
and the clip, with an optional explicit target. No LLM, no network: the same
inputs must always yield the same copy.
"""
import pytest
from clipwright.pipeline import bridge, profiles
TARGET = "https://www.youtube.com/watch?v=LONGFORM123"
@pytest.fixture(scope="module")
def cseea():
return profiles.load_profile("cseea")
def _clip():
return {"video_title_for_youtube_short": "I broke the world",
"viral_hook_text": "I broke the world in one block"}
def test_explicit_target_reaches_every_field(cseea):
result = bridge.build_bridge(cseea, clip=_clip(), related_video_url=TARGET)
assert result["related_video_url"] == TARGET
assert TARGET in result["description_bridge"]
assert TARGET in result["first_comment"]
assert any(TARGET in step for step in result["checklist"])
assert result["manual_pin_required"] is True
def test_checklist_names_the_manual_studio_steps(cseea):
result = bridge.build_bridge(cseea, clip=_clip(), related_video_url=TARGET)
joined = "\n".join(result["checklist"])
assert "Studio" in joined
assert "Related video" in joined
assert "Pin" in joined
assert "no api" in joined.lower()
def test_no_target_uses_profile_links_and_invents_no_url(cseea):
result = bridge.build_bridge(cseea, clip=_clip(), related_video_url=None)
assert result["related_video_url"] is None
# The channel's own links still appear; no watch URL is fabricated.
assert "youtube.com/@cseea" in result["description_bridge"]
assert "youtube.com/@cseea" in result["first_comment"]
assert "watch?v=" not in result["description_bridge"]
# The checklist tells the operator to paste the target themselves.
assert any("paste" in step.lower() for step in result["checklist"])
def test_published_history_supplies_the_target_when_none_given():
profile = profiles.Profile(
slug="t",
description_template="{hook}\n\nFull video: {link}",
links=["https://example.com/channel"],
published_video_history=[
{"id": "OLD", "published_at": "2026-01-01"},
{"id": "NEW", "published_at": "2026-06-01"},
],
)
result = bridge.build_bridge(profile, clip=_clip())
assert result["related_video_url"] == "https://www.youtube.com/watch?v=NEW"
assert "watch?v=NEW" in result["first_comment"]
def test_explicit_target_wins_over_history_and_url_field_preferred():
profile = profiles.Profile(
slug="t",
published_video_history=[{"url": "https://youtu.be/HISTORY"}],
)
assert bridge.target_video(profile, TARGET) == TARGET
assert bridge.target_video(profile) == "https://youtu.be/HISTORY"
def test_profiles_produce_different_bridge_copy(cseea):
pedro = profiles.load_profile("pedro")
cseea_bridge = bridge.build_bridge(cseea, clip=_clip(), related_video_url=TARGET)
pedro_bridge = bridge.build_bridge(pedro, clip=_clip(), related_video_url=TARGET)
assert cseea_bridge["description_bridge"] != pedro_bridge["description_bridge"]
assert "#minecraft" in cseea_bridge["description_bridge"]
assert "Chapters and source" in pedro_bridge["description_bridge"]
def test_no_profile_still_produces_usable_copy():
result = bridge.build_bridge(None, clip=_clip(), related_video_url=TARGET)
assert TARGET in result["first_comment"]
assert TARGET in result["description_bridge"]
assert result["checklist"] # never empty
def test_bridge_fields_merge_into_clip_metadata(cseea):
"""The exact merge ``main.py`` performs must land every bridge field."""
clip = _clip()
clip.update(bridge.build_bridge(cseea, clip=clip, related_video_url=TARGET))
assert set(bridge.build_bridge(cseea, clip=clip).keys()) <= set(clip.keys())
assert clip["related_video_url"] == TARGET
assert isinstance(clip["checklist"], list)
assert isinstance(clip["description_bridge"], str) and clip["description_bridge"]
assert isinstance(clip["first_comment"], str) and clip["first_comment"]

View file

@ -0,0 +1,132 @@
"""Bridge copy + opt-in first-comment endpoints (PLAN #6).
Confirms the generated copy/checklist is exposed from clip metadata, that the
comment endpoint is guarded when the YouTube Data API is unconfigured (clear
error, no post), and that posting only happens when the caller opts in.
"""
import asyncio
import json
import httpx
import pytest
app_module = pytest.importorskip("clipwright.api.app")
from clipwright.integrations import youtube_data # noqa: E402
JOB_ID = "bridge-endpoint-test-job"
TARGET = "https://www.youtube.com/watch?v=LONGFORM123"
CHECKLIST = [
"Open YouTube Studio -> Content -> this Short -> Edit.",
f"Details -> Related video: set it to {TARGET} (no API).",
"Post the generated first comment.",
"Pin the first comment (no API).",
]
def _request(method, path, json_body=None):
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.request(method, path, json=json_body)
return asyncio.run(_do())
@pytest.fixture()
def job(tmp_path, monkeypatch):
out_root = tmp_path / "output"
job_dir = out_root / JOB_ID
job_dir.mkdir(parents=True)
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
clip = {
"start": 0.0, "end": 30.0,
"video_title_for_youtube_short": "I broke the world",
"video_url": f"/videos/{JOB_ID}/mytitle_clip_1.mp4",
# The fields main.py merges into clip metadata before writing.
"related_video_url": TARGET,
"description_bridge": f"▶ Full video: {TARGET}",
"first_comment": f"▶ Full video: {TARGET}",
"checklist": CHECKLIST,
"manual_pin_required": True,
}
meta = {"shorts": [clip], "transcript": {"language": "none", "segments": []},
"source_video": "src.mp4", "output_format": "auto"}
(job_dir / "mytitle_metadata.json").write_text(json.dumps(meta))
app_module.jobs[JOB_ID] = {
"status": "completed", "logs": [],
"result": {"clips": [dict(clip)]}, "user_id": None,
}
try:
yield {"dir": job_dir, "meta_path": job_dir / "mytitle_metadata.json"}
finally:
app_module.jobs.pop(JOB_ID, None)
@pytest.fixture()
def unconfigured(monkeypatch):
for name in (youtube_data.CLIENT_ID_ENV, youtube_data.CLIENT_SECRET_ENV,
youtube_data.REFRESH_TOKEN_ENV):
monkeypatch.delenv(name, raising=False)
class TestBridgeCopyEndpoint:
def test_returns_generated_copy_and_checklist(self, job, unconfigured):
resp = _request("GET", f"/api/clip/{JOB_ID}/0/bridge")
assert resp.status_code == 200
data = resp.json()
assert data["related_video_url"] == TARGET
assert TARGET in data["description_bridge"]
assert TARGET in data["first_comment"]
assert data["checklist"] == CHECKLIST
assert data["manual_pin_required"] is True
assert data["comment_api_configured"] is False
def test_unknown_clip_is_404(self, job, unconfigured):
resp = _request("GET", f"/api/clip/{JOB_ID}/99/bridge")
assert resp.status_code == 404
class TestBridgeCommentEndpoint:
def test_unconfigured_is_a_clear_400_and_posts_nothing(self, job, unconfigured,
monkeypatch):
calls = []
monkeypatch.setattr(app_module.youtube_data, "post_first_comment",
lambda *a, **k: calls.append((a, k)))
resp = _request("POST", f"/api/clip/{JOB_ID}/0/bridge/comment",
{"video_id": "short-1"})
assert resp.status_code == 400
assert "not configured" in resp.json()["detail"]
assert calls == []
def test_configured_posts_the_first_comment(self, job, monkeypatch):
monkeypatch.setenv(youtube_data.CLIENT_ID_ENV, "cid")
monkeypatch.setenv(youtube_data.CLIENT_SECRET_ENV, "secret")
monkeypatch.setenv(youtube_data.REFRESH_TOKEN_ENV, "refresh")
calls = []
def fake_post(video_id, text):
calls.append((video_id, text))
return {"id": "comment-1"}
monkeypatch.setattr(app_module.youtube_data, "post_first_comment", fake_post)
resp = _request("POST", f"/api/clip/{JOB_ID}/0/bridge/comment",
{"video_id": "short-1"})
assert resp.status_code == 200
assert resp.json()["posted"] is True
assert resp.json()["comment_id"] == "comment-1"
assert resp.json()["manual_pin_required"] is True
# The generated first_comment was used; posting is explicit, not auto.
assert calls == [("short-1", f"▶ Full video: {TARGET}")]
def test_caller_can_override_the_comment_text(self, job, monkeypatch):
monkeypatch.setenv(youtube_data.CLIENT_ID_ENV, "cid")
monkeypatch.setenv(youtube_data.CLIENT_SECRET_ENV, "secret")
monkeypatch.setenv(youtube_data.REFRESH_TOKEN_ENV, "refresh")
monkeypatch.setattr(app_module.youtube_data, "post_first_comment",
lambda video_id, text: {"id": "c"})
resp = _request("POST", f"/api/clip/{JOB_ID}/0/bridge/comment",
{"video_id": "short-1", "text": "custom"})
assert resp.status_code == 200

View file

@ -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"}]}

View file

@ -154,7 +154,7 @@ class TestDetailPromptCarriesTheCount:
low, high = clip_count_targets(5) low, high = clip_count_targets(5)
prompt = gw.DETAIL_PROMPT_TEMPLATE.format( prompt = gw.DETAIL_PROMPT_TEMPLATE.format(
video_duration=300, language="es", min_clips=low, max_clips=high, video_duration=300, language="es", min_clips=low, max_clips=high,
min_secs=15.0, max_secs=60.0, windows_json="[]") min_secs=15.0, max_secs=60.0, profile_rules="", windows_json="[]")
assert f"return {low} to {high} clips" in prompt assert f"return {low} to {high} clips" in prompt
assert "15 to 60 seconds" in prompt assert "15 to 60 seconds" in prompt
# The JSON schema example legitimately keeps braces (they are {{ }} in # The JSON schema example legitimately keeps braces (they are {{ }} in

231
tests/test_code_layout.py Normal file
View file

@ -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]")

View file

@ -64,7 +64,7 @@ class TestPromptTemplates:
def test_detail_template_carries_the_band(self): def test_detail_template_carries_the_band(self):
text = _templates()["DETAIL_PROMPT_TEMPLATE"].format( text = _templates()["DETAIL_PROMPT_TEMPLATE"].format(
video_duration=100, language="es", min_clips=2, max_clips=4, video_duration=100, language="es", min_clips=2, max_clips=4,
min_secs=10.0, max_secs=20.0, windows_json="[]") min_secs=10.0, max_secs=20.0, profile_rules="", windows_json="[]")
assert "10 to 20 seconds" in text assert "10 to 20 seconds" in text
assert "return 2 to 4 clips" in text assert "return 2 to 4 clips" in text

166
tests/test_handoff.py Normal file
View file

@ -0,0 +1,166 @@
"""Cadence handoff ingest (PLAN #8): manifest validation + word merging.
These exercise ``main.load_handoff_transcript`` directly. The CLI/e2e wiring
(real ffmpeg, handoff actually skipping ASR) lives under ``tests/e2e``.
"""
import json
import pytest
main = pytest.importorskip("clipwright.pipeline.main") # needs cv2/mediapipe stubs
def _write(path, data):
path.write_text(json.dumps(data), encoding="utf-8")
return path
def _transcript(words):
return {
"text": " So the -Kanal.",
"language": "en",
"segments": [{"start": 0.0, "end": 0.8, "text": " So the -Kanal.",
"words": words}],
}
WORDS = [
{"word": " So", "start": 0.0, "end": 0.3},
{"word": " the", "start": 0.3, "end": 0.5},
{"word": "-Kanal.", "start": 0.5, "end": 0.8},
]
def _manifest(tmp_path, *, duration=6.0, transcript_rel="recording.transcript.json",
schema="clipwright.handoff/1", transcript_ref=None):
return {
"schema": schema,
"generator": {"name": "cadence", "version": "0.1.0"},
"edited": {"timeline": "voice-audio", "duration": duration, "master": None},
"sources": [{"index": 0, "path": "/abs/recordings/rec.mkv", "duration": 612.3}],
"transcript": transcript_ref if transcript_ref is not None
else {"path": transcript_rel},
"candidates": [],
"chapters": [],
}
# --- happy path ------------------------------------------------------------
def test_handoff_loads_and_merges_continuation_words(tmp_path):
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path))
_write(tmp_path / "recording.transcript.json", _transcript(WORDS))
result = main.load_handoff_transcript(
tmp_path / "recording.handoff.json", tmp_path / "master.mp4", 6.0)
words = result["segments"][0]["words"]
# The leading-space tokens stay boundaries; "-Kanal." (no leading space)
# glues onto " the" and extends its end.
assert [w["word"] for w in words] == [" So", " the-Kanal."]
assert words[1]["end"] == 0.8
def test_transcript_path_resolves_relative_to_the_manifest(tmp_path):
sub = tmp_path / "bundle"
sub.mkdir()
_write(sub / "rec.handoff.json", _manifest(tmp_path, transcript_rel="rec.transcript.json"))
_write(sub / "rec.transcript.json", _transcript(WORDS))
result = main.load_handoff_transcript(sub / "rec.handoff.json", "master.mp4", 5.99)
assert result["segments"]
def test_missing_words_list_is_tolerated(tmp_path):
transcript = {"language": "en",
"segments": [{"start": 0.0, "end": 1.0, "text": " no words"}]}
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path))
_write(tmp_path / "recording.transcript.json", transcript)
result = main.load_handoff_transcript(
tmp_path / "recording.handoff.json", "master.mp4", 6.0)
assert "words" not in result["segments"][0]
# --- failure modes ---------------------------------------------------------
def test_missing_manifest_is_refused(tmp_path):
with pytest.raises(main.HandoffError) as exc:
main.load_handoff_transcript(tmp_path / "nope.json", "master.mp4", 6.0)
assert "not found" in str(exc.value)
def test_malformed_manifest_json_is_refused(tmp_path):
(tmp_path / "bad.handoff.json").write_text("{ not json", encoding="utf-8")
with pytest.raises(main.HandoffError) as exc:
main.load_handoff_transcript(tmp_path / "bad.handoff.json", "master.mp4", 6.0)
assert "malformed handoff manifest" in str(exc.value)
def test_missing_transcript_is_refused(tmp_path):
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path))
with pytest.raises(main.HandoffError) as exc:
main.load_handoff_transcript(
tmp_path / "recording.handoff.json", "master.mp4", 6.0)
assert "transcript not found" in str(exc.value)
def test_manifest_without_transcript_path_is_refused(tmp_path):
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path, transcript_ref={}))
with pytest.raises(main.HandoffError) as exc:
main.load_handoff_transcript(
tmp_path / "recording.handoff.json", "master.mp4", 6.0)
assert "transcript.path" in str(exc.value)
def test_transcript_without_segments_is_refused(tmp_path):
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path))
_write(tmp_path / "recording.transcript.json", {"language": "en", "segments": []})
with pytest.raises(main.HandoffError) as exc:
main.load_handoff_transcript(
tmp_path / "recording.handoff.json", "master.mp4", 6.0)
assert "no segments" in str(exc.value)
def test_unknown_schema_is_refused(tmp_path):
_write(tmp_path / "recording.handoff.json",
_manifest(tmp_path, schema="something.else/9"))
_write(tmp_path / "recording.transcript.json", _transcript(WORDS))
with pytest.raises(main.HandoffError) as exc:
main.load_handoff_transcript(
tmp_path / "recording.handoff.json", "master.mp4", 6.0)
assert "unsupported handoff schema" in str(exc.value)
# --- duration gate ---------------------------------------------------------
@pytest.mark.parametrize("measured", [5.96, 6.0, 6.04])
def test_duration_within_one_percent_passes(tmp_path, measured):
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path, duration=6.0))
_write(tmp_path / "recording.transcript.json", _transcript(WORDS))
assert main.load_handoff_transcript(
tmp_path / "recording.handoff.json", "master.mp4", measured)["segments"]
def test_duration_mismatch_refuses_and_points_at_transcript(tmp_path):
_write(tmp_path / "recording.handoff.json", _manifest(tmp_path, duration=6.0))
_write(tmp_path / "recording.transcript.json", _transcript(WORDS))
with pytest.raises(main.HandoffError) as exc:
main.load_handoff_transcript(
tmp_path / "recording.handoff.json", "master.mp4", 7.5)
message = str(exc.value)
assert "refusing the handoff" in message
assert "--transcript" in message
# --- never opens source paths ----------------------------------------------
def test_source_paths_are_never_opened(tmp_path):
# A remote manifest may name any path; the loader must not touch it.
manifest = _manifest(tmp_path)
manifest["sources"] = [{"index": 0, "path": str(tmp_path / "does-not-exist.mkv")}]
manifest["edited"]["master"] = {"path": str(tmp_path / "also-missing.mp4")}
_write(tmp_path / "recording.handoff.json", manifest)
_write(tmp_path / "recording.transcript.json", _transcript(WORDS))
assert main.load_handoff_transcript(
tmp_path / "recording.handoff.json", "master.mp4", 6.0)["segments"]

177
tests/test_handoff_api.py Normal file
View file

@ -0,0 +1,177 @@
"""Cadence handoff bundle staging at the API edge (PLAN #8).
Only the bundle transport is exercised here (ZIP in an /api/uploads slot); the
CLI validation of the manifest is covered by tests/test_handoff.py and the
tiny-video run under tests/e2e/pipeline.
"""
import asyncio
import io
import json
import zipfile
from pathlib import Path
import httpx
import pytest
app = pytest.importorskip("clipwright.api.app")
def _zip_bytes(entries):
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
for name, data in entries.items():
zf.writestr(name, data)
return buf.getvalue()
def _manifest_bytes(transcript_ref="rec.transcript.json",
schema="clipwright.handoff/1"):
return json.dumps({
"schema": schema,
"generator": {"name": "cadence", "version": "0.1.0"},
"edited": {"duration": 6.0, "master": None},
"sources": [{"index": 0, "path": "/abs/rec.mkv"}],
"transcript": {"path": transcript_ref},
"candidates": [],
}).encode("utf-8")
def _transcript_bytes():
return json.dumps({
"text": "hello",
"language": "en",
"segments": [{"start": 0.0, "end": 1.0, "text": " hello",
"words": [{"word": " hello", "start": 0.0, "end": 1.0}]}],
}).encode("utf-8")
def _job_dir(tmp_path):
job = tmp_path / "job"
job.mkdir()
return job
# --- staging ---------------------------------------------------------------
def test_stages_manifest_and_transcript_into_the_job_dir(tmp_path):
job = _job_dir(tmp_path)
bundle = tmp_path / "bundle.zip"
bundle.write_bytes(_zip_bytes({
"rec.handoff.json": _manifest_bytes(),
"rec.transcript.json": _transcript_bytes(),
}))
manifest_path = app._stage_handoff_bundle(str(bundle), str(job))
assert manifest_path == str(job / "cadence_handoff.json")
staged = json.loads(Path(manifest_path).read_text())
assert staged["transcript"]["path"] == "source_transcript.json"
assert staged["edited"]["duration"] == 6.0
transcript = json.loads((job / "source_transcript.json").read_text())
assert transcript["segments"]
def test_manifest_found_by_schema_when_not_named_handoff_json(tmp_path):
job = _job_dir(tmp_path)
bundle = tmp_path / "bundle.zip"
bundle.write_bytes(_zip_bytes({
"cadence-manifest.json": _manifest_bytes(),
"rec.transcript.json": _transcript_bytes(),
}))
manifest_path = app._stage_handoff_bundle(str(bundle), str(job))
assert Path(manifest_path).exists()
def test_member_paths_cannot_escape_the_job_dir(tmp_path):
job = _job_dir(tmp_path)
bundle = tmp_path / "bundle.zip"
bundle.write_bytes(_zip_bytes({
"../evil.handoff.json": _manifest_bytes(),
"../rec.transcript.json": _transcript_bytes(),
}))
app._stage_handoff_bundle(str(bundle), str(job))
assert not (tmp_path / "evil.handoff.json").exists()
assert not (tmp_path / "rec.transcript.json").exists()
assert (job / "cadence_handoff.json").exists()
def test_non_zip_bundle_is_400(tmp_path):
job = _job_dir(tmp_path)
not_a_zip = tmp_path / "bundle.bin"
not_a_zip.write_bytes(b"not a zip")
with pytest.raises(app.HTTPException) as exc:
app._stage_handoff_bundle(str(not_a_zip), str(job))
assert exc.value.status_code == 400
assert "ZIP" in exc.value.detail
def test_bundle_without_a_manifest_is_400(tmp_path):
job = _job_dir(tmp_path)
bundle = tmp_path / "bundle.zip"
bundle.write_bytes(_zip_bytes({"rec.transcript.json": _transcript_bytes()}))
with pytest.raises(app.HTTPException) as exc:
app._stage_handoff_bundle(str(bundle), str(job))
assert exc.value.status_code == 400
assert "manifest" in exc.value.detail
def test_manifest_referencing_a_missing_transcript_is_400(tmp_path):
job = _job_dir(tmp_path)
bundle = tmp_path / "bundle.zip"
bundle.write_bytes(_zip_bytes({"rec.handoff.json": _manifest_bytes()}))
with pytest.raises(app.HTTPException) as exc:
app._stage_handoff_bundle(str(bundle), str(job))
assert exc.value.status_code == 400
assert "not in the bundle" in exc.value.detail
def test_transcript_without_segments_is_400(tmp_path):
job = _job_dir(tmp_path)
bundle = tmp_path / "bundle.zip"
bundle.write_bytes(_zip_bytes({
"rec.handoff.json": _manifest_bytes(),
"rec.transcript.json": json.dumps({"segments": []}).encode(),
}))
with pytest.raises(app.HTTPException) as exc:
app._stage_handoff_bundle(str(bundle), str(job))
assert exc.value.status_code == 400
assert "no segments" in exc.value.detail
# --- /api/uploads handoff slot ---------------------------------------------
def _client_call(method, path, **kw):
async def _do():
transport = httpx.ASGITransport(app=app.app)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as c:
return await getattr(c, method)(path, **kw)
return asyncio.run(_do())
def test_handoff_slot_stores_a_zip_without_a_duration_probe(tmp_path, monkeypatch):
uploads = tmp_path / "uploads"
uploads.mkdir()
monkeypatch.setattr(app, "UPLOAD_DIR", str(uploads))
monkeypatch.setattr(app, "pending_uploads", {})
created = _client_call("post", "/api/uploads",
json={"filename": "bundle.zip", "kind": "handoff"})
assert created.status_code == 200
assert created.json()["kind"] == "handoff"
upload_id = created.json()["upload_id"]
bundle = _zip_bytes({
"rec.handoff.json": _manifest_bytes(),
"rec.transcript.json": _transcript_bytes(),
})
put = _client_call("put", f"/api/uploads/{upload_id}", content=bundle)
assert put.status_code == 200
assert put.json()["kind"] == "handoff"
assert "duration_seconds" not in put.json()
def test_unknown_upload_kind_is_400(tmp_path, monkeypatch):
monkeypatch.setattr(app, "pending_uploads", {})
resp = _client_call("post", "/api/uploads",
json={"filename": "x.mp4", "kind": "nonsense"})
assert resp.status_code == 400

170
tests/test_hook_start.py Normal file
View file

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

View file

@ -101,7 +101,8 @@ class TestPick:
class TestValidDecisions: class TestValidDecisions:
def test_every_valid_decision_maps_to_known_modules(self): 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: for decision in layout_picker.VALID:
assert set(_module_flags(decision)) <= known assert set(_module_flags(decision)) <= known

View file

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

214
tests/test_profiles.py Normal file
View file

@ -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/<slug>.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") == []

157
tests/test_provenance.py Normal file
View file

@ -0,0 +1,157 @@
"""Retention provenance (PLAN #10): one versioned record per clip.
Instrumentation only. Every clip carries its active profile, predicted score,
start-boundary path (#2a hook-first vs the plain word snap), #6 bridge target
and publish target, so the future retention/analytics loop is a data pull rather
than a re-architecture. The loop itself is deliberately not built here.
"""
import asyncio
import json
import httpx
import pytest
main = pytest.importorskip("clipwright.pipeline.main")
from clipwright.pipeline import bridge, profiles # noqa: E402
def _clip():
return {
"start": 12.3, "end": 42.3,
"predicted_score": 85,
"video_title_for_youtube_short": "I broke the world",
"viral_hook_text": "I broke the world in one block",
}
class TestBuildProvenance:
def test_schema_version_and_keys_without_profile(self):
prov = main.build_provenance(_clip(), None)
assert prov["schema_version"] == main.PROVENANCE_SCHEMA_VERSION == 1
assert set(prov) == {"schema_version", "profile", "predicted_score",
"hook", "bridge", "publish"}
assert prov["profile"] is None
assert prov["predicted_score"] == 85
assert prov["publish"]["postiz_integration_id"] is None
assert set(prov["hook"]) == {"applied", "source", "start", "trim",
"proposed"}
assert set(prov["bridge"]) == {"present", "related_video_url"}
def test_profile_and_publish_target_are_recorded(self):
profile = profiles.Profile(
slug="cseea", default_postiz_integration_id="postiz-42")
prov = main.build_provenance(_clip(), profile)
assert prov["profile"] == "cseea"
assert prov["publish"]["postiz_integration_id"] == "postiz-42"
def test_hook_first_boundary_is_reused(self):
clip = _clip()
clip["hook_first"] = {"start": 10.0, "trim": 2.3, "proposed": 12.3}
prov = main.build_provenance(clip, None)
assert prov["hook"] == {"applied": True, "source": "hook_first",
"start": 10.0, "trim": 2.3, "proposed": 12.3}
def test_plain_snap_boundary_is_marked_when_no_hook_moved_it(self):
prov = main.build_provenance(_clip(), None)
assert prov["hook"]["applied"] is False
assert prov["hook"]["source"] == "snap"
assert prov["hook"]["start"] is None
assert prov["hook"]["trim"] is None
assert prov["hook"]["proposed"] is None
def test_bridge_presence_and_related_target(self):
clip = _clip()
assert main.build_provenance(clip, None)["bridge"]["present"] is False
target = "https://www.youtube.com/watch?v=LONGFORM123"
clip.update(bridge.build_bridge(None, clip=clip,
related_video_url=target))
prov = main.build_provenance(clip, None)
assert prov["bridge"] == {"present": True,
"related_video_url": target}
def test_metadata_merge_is_additive_and_round_trips(self):
"""The exact main.py sequence: bridge fields then provenance, JSON-safe."""
profile = profiles.load_profile("cseea")
clip = _clip()
before = set(clip)
clip.update(bridge.build_bridge(profile, clip=clip,
related_video_url="https://youtu.be/x"))
clip["provenance"] = main.build_provenance(clip, profile)
# Additive: the original keys survive untouched.
assert before <= set(clip)
data = {"shorts": [clip]}
reloaded = json.loads(json.dumps(data))
prov = reloaded["shorts"][0]["provenance"]
assert prov["schema_version"] == 1
assert prov["profile"] == "cseea"
assert set(prov) == {"schema_version", "profile", "predicted_score",
"hook", "bridge", "publish"}
app_module = pytest.importorskip("clipwright.api.app")
JOB_ID = "provenance-endpoint-test-job"
def _request(method, 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.request(method, path)
return asyncio.run(_do())
@pytest.fixture()
def job(tmp_path, monkeypatch):
out_root = tmp_path / "output"
job_dir = out_root / JOB_ID
job_dir.mkdir(parents=True)
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
clip = {"start": 0.0, "end": 30.0,
"provenance": main.build_provenance(
{"start": 0.0, "end": 30.0, "predicted_score": 77}, None)}
meta = {"shorts": [clip],
"transcript": {"language": "none", "segments": []}}
(job_dir / "mytitle_metadata.json").write_text(json.dumps(meta))
app_module.jobs[JOB_ID] = {"status": "completed", "logs": [],
"result": {"clips": [dict(clip)]},
"user_id": None}
try:
yield job_dir
finally:
app_module.jobs.pop(JOB_ID, None)
class TestProvenanceEndpoint:
def test_returns_the_versioned_record(self, job):
resp = _request("GET", f"/api/clip/{JOB_ID}/0/provenance")
assert resp.status_code == 200
data = resp.json()
assert data["schema_version"] == 1
assert data["provenance"]["predicted_score"] == 77
assert data["provenance"]["hook"]["source"] == "snap"
def test_old_clip_without_a_record_is_404(self, tmp_path, monkeypatch):
out_root = tmp_path / "output2"
job_dir = out_root / "old-job"
job_dir.mkdir(parents=True)
monkeypatch.setattr(app_module, "OUTPUT_DIR", str(out_root))
meta = {"shorts": [{"start": 0.0, "end": 30.0}],
"transcript": {"language": "none", "segments": []}}
(job_dir / "mytitle_metadata.json").write_text(json.dumps(meta))
app_module.jobs["old-job"] = {"status": "completed", "logs": [],
"result": {"clips": [{"start": 0.0}]},
"user_id": None}
try:
resp = _request("GET", "/api/clip/old-job/0/provenance")
assert resp.status_code == 404
assert "No provenance" in resp.json()["detail"]
finally:
app_module.jobs.pop("old-job", None)
def test_unknown_clip_is_404(self, job):
resp = _request("GET", f"/api/clip/{JOB_ID}/99/provenance")
assert resp.status_code == 404

View file

@ -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) == []

View file

@ -56,9 +56,11 @@ def test_normalise_concepts_clamps_and_pads():
] ]
out = thumbnail.normalise_concepts(raw, 3, "My title", thumbnail_text_hint="hint") out = thumbnail.normalise_concepts(raw, 3, "My title", thumbnail_text_hint="hint")
assert len(out) == 3 assert len(out) == 3
assert out[0] == {"text": "ESTO FUNCIONA", "text_position": "left", "text_color": "white", assert out[0]["text"] == "ESTO FUNCIONA"
"scene": "a desk", "why": ""} assert out[0]["text_position"] == "left"
assert out[1]["why"] == "fallback" and out[1]["text"] == "HINT" # #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(): def test_parse_json_tolerates_fences_and_prose():

View file

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

130
tests/test_youtube_data.py Normal file
View file

@ -0,0 +1,130 @@
"""``integrations.youtube_data`` (PLAN #6): mocked HTTP, never live OAuth.
Every call goes through an ``httpx.Client`` built on a ``MockTransport``, so no
network is touched. The unconfigured path must be a hard no-op: not one request.
"""
import json
import httpx
import pytest
from clipwright.integrations import youtube_data
def _configure(monkeypatch):
monkeypatch.setenv(youtube_data.CLIENT_ID_ENV, "cid")
monkeypatch.setenv(youtube_data.CLIENT_SECRET_ENV, "secret")
monkeypatch.setenv(youtube_data.REFRESH_TOKEN_ENV, "refresh")
monkeypatch.setenv(youtube_data.TOKEN_URI_ENV, "https://oauth.test/token")
def _unconfigure(monkeypatch):
for name in (youtube_data.CLIENT_ID_ENV, youtube_data.CLIENT_SECRET_ENV,
youtube_data.REFRESH_TOKEN_ENV):
monkeypatch.delenv(name, raising=False)
class _Recorder:
"""Records requests and answers the token + comment calls."""
def __init__(self, token_status=200, comment_status=200,
comment_json=None):
self.requests = []
self.token_status = token_status
self.comment_status = comment_status
self.comment_json = comment_json or {
"id": "comment-1",
"snippet": {"videoId": "short-1"},
}
def handler(self, request):
self.requests.append(request)
if request.url.path.endswith("/token"):
return httpx.Response(self.token_status, json={"access_token": "tok"})
return httpx.Response(self.comment_status, json=self.comment_json)
def client(self):
return httpx.Client(transport=httpx.MockTransport(self.handler))
def test_is_configured_tracks_env(monkeypatch):
_unconfigure(monkeypatch)
assert youtube_data.is_configured() is False
_configure(monkeypatch)
assert youtube_data.is_configured() is True
def test_unconfigured_is_a_noop_and_makes_no_request(monkeypatch):
_unconfigure(monkeypatch)
recorder = _Recorder()
with pytest.raises(youtube_data.YoutubeDataError) as exc:
youtube_data.post_first_comment("short-1", "hello", client=recorder.client())
assert exc.value.status_code == 400
assert "not configured" in exc.value.detail
assert recorder.requests == []
def test_posts_first_comment_with_refresh_token(monkeypatch):
_configure(monkeypatch)
recorder = _Recorder()
result = youtube_data.post_first_comment(
"short-1", "watch the full video", client=recorder.client())
assert result["id"] == "comment-1"
assert [r.method for r in recorder.requests] == ["POST", "POST"]
token_req, comment_req = recorder.requests
assert token_req.url == "https://oauth.test/token"
assert b"grant_type=refresh_token" in token_req.content
assert b"refresh_token=refresh" in token_req.content
assert comment_req.url.path.endswith("/commentThreads")
assert comment_req.url.params["part"] == "snippet"
assert comment_req.headers["authorization"] == "Bearer tok"
body = json.loads(comment_req.content)
assert body["snippet"]["videoId"] == "short-1"
assert (body["snippet"]["topLevelComment"]["snippet"]["textOriginal"]
== "watch the full video")
def test_token_failure_is_reported_without_posting(monkeypatch):
_configure(monkeypatch)
recorder = _Recorder(token_status=401)
with pytest.raises(youtube_data.YoutubeDataError) as exc:
youtube_data.post_first_comment("short-1", "hi", client=recorder.client())
assert exc.value.status_code == 502
assert "token refresh failed" in exc.value.detail
assert len(recorder.requests) == 1 # never reached commentThreads
def test_comment_error_carries_status_and_truncated_body(monkeypatch):
_configure(monkeypatch)
recorder = _Recorder(comment_status=403)
with pytest.raises(youtube_data.YoutubeDataError) as exc:
youtube_data.post_first_comment("short-1", "hi", client=recorder.client())
assert exc.value.status_code == 403
assert "commentThreads.insert failed" in exc.value.detail
def test_server_error_maps_to_502(monkeypatch):
_configure(monkeypatch)
recorder = _Recorder(comment_status=500)
with pytest.raises(youtube_data.YoutubeDataError) as exc:
youtube_data.post_first_comment("short-1", "hi", client=recorder.client())
assert exc.value.status_code == 502
def test_missing_inputs_are_refused(monkeypatch):
_configure(monkeypatch)
recorder = _Recorder()
client = recorder.client()
with pytest.raises(youtube_data.YoutubeDataError):
youtube_data.post_first_comment("", "hi", client=client)
with pytest.raises(youtube_data.YoutubeDataError):
youtube_data.post_first_comment("short-1", " ", client=client)
assert recorder.requests == []
def test_scope_is_force_ssl():
# commentThreads.insert requires force-ssl; documented so a refactor cannot
# silently drop it.
assert youtube_data.SCOPE == "https://www.googleapis.com/auth/youtube.force-ssl"