feat/youtube-growth-toolkit #8

Merged
pedro-bento merged 10 commits from feat/youtube-growth-toolkit into main 2026-10-05 20:33:57 +01:00
11 changed files with 1401 additions and 25 deletions
Showing only changes of commit 79341f0a38 - Show all commits

View file

@ -1,5 +1,5 @@
import os
from clipwright.pipeline import llm_backend
from clipwright.pipeline import llm_backend, profiles
import re
import sys
import uuid
@ -29,7 +29,7 @@ import httpx
from clipwright.media import recut
from clipwright.layouts import layout_ranges
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
load_dotenv()
@ -1518,6 +1518,11 @@ def _safe_under(base_dir: str, user_rel_path: str) -> Optional[str]:
class ProcessRequest(BaseModel):
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
# 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(),
}
@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:
"""Run quality_probe.py in a worker thread; {} on any failure (fail-open)."""
def _run():
@ -1851,6 +1868,7 @@ def _reject_short_source(duration: float):
LAYOUT_ENV = {
"split": "SPLIT_LAYOUT", # two speakers stacked
"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
"punch_in": "PUNCH_IN", # small push on the clip's beats
}
@ -1883,17 +1901,27 @@ def _upload_url_base(request):
@app.post("/api/uploads")
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)
try:
body = await request.json()
except Exception:
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())
pending_uploads[upload_id] = {
"user_id": user_id,
"filename": filename,
"kind": kind,
"path": os.path.join(UPLOAD_DIR, f"pending_{upload_id}_{filename}"),
"created": time.time(),
"bytes": 0,
@ -1901,6 +1929,7 @@ async def create_upload(request: Request):
}
return {
"upload_id": upload_id,
"kind": kind,
"upload_url": f"{_upload_url_base(request)}/api/uploads/{upload_id}",
"method": "PUT",
"max_mb": MAX_FILE_SIZE_MB,
@ -1934,12 +1963,18 @@ async def put_upload(upload_id: str, request: Request):
os.remove(slot["path"])
raise HTTPException(status_code=400, detail="Empty body")
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"])
if duration <= 0:
os.remove(slot["path"])
slot["complete"] = False
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."}
@ -1983,6 +2018,106 @@ def _take_pending_upload(upload_id, user_id):
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):
"""Env overrides for the layouts this job allows. Unknown names are ignored
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),
upload_id: 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)
if not api_key and not llm_backend.active():
@ -2064,6 +2202,9 @@ async def process_endpoint(
captions = body.get("captions")
upload_id = body.get("upload_id")
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).
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.
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
# the subprocess, so they must be set before Popen.
chosen = layout_env(layouts)
@ -2281,6 +2447,20 @@ async def process_endpoint(
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])
if output_format and output_format != "auto":
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):
start: float
end: float
@ -4473,12 +4787,29 @@ async def thumbnail_upload(
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")
async def thumbnail_analyze(
request: Request,
file: Optional[UploadFile] = File(None),
url: 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")
):
"""Analyze a video and suggest viral YouTube titles."""
@ -4486,6 +4817,9 @@ async def thumbnail_analyze(
if not api_key:
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
# Check for pre-existing session with background Whisper
@ -4536,7 +4870,10 @@ async def thumbnail_analyze(
try:
# Run analysis in thread pool (skips Whisper if pre_transcript is available)
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
if session_id not in thumbnail_sessions:
@ -4647,6 +4984,7 @@ async def thumbnail_generate(
count: int = Form(3),
burn_text: bool = Form(True),
frame: str = Form(""),
channel: Optional[str] = Form(None),
face: Optional[UploadFile] = File(None),
background: Optional[UploadFile] = File(None),
):
@ -4661,6 +4999,9 @@ async def thumbnail_generate(
if not api_key:
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
# owner may generate from it.
_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,
extra_prompt, count, video_context, burn_text=burn_text,
thumbnail_text_hint=text_hint, language=language,
frame_reference=frame_reference),
frame_reference=frame_reference, profile=profile),
)
if not thumbnails:
@ -4765,6 +5106,7 @@ async def thumbnail_frames(session_id: str, request: Request):
class ThumbnailDescribeRequest(BaseModel):
session_id: str
title: str
channel: Optional[str] = None
@app.post("/api/thumbnail/describe")
async def thumbnail_describe(
@ -4776,6 +5118,9 @@ async def thumbnail_describe(
if not api_key:
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:
raise HTTPException(status_code=404, detail="Session not found")
@ -4789,12 +5134,15 @@ async def thumbnail_describe(
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(
None,
functools.partial(
generate_youtube_description,
api_key,
req.title,
segments,
session.get("language", "en"),
session.get("video_duration", 0)
session.get("video_duration", 0),
profile=profile,
),
)
return {"description": result.get("description", "")}

View file

@ -157,6 +157,13 @@ Pick ONE layout:
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
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
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.
@ -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
clip — the specific hook, claim, number or payoff, not the topic.
TRANSCRIPT_LANGUAGE: {language}
{profile_rules}TRANSCRIPT_LANGUAGE: {language}
VIDEO_DURATION_SECONDS: {video_duration}
CANDIDATE_WINDOWS_JSON:
{windows_json}

View file

@ -21,12 +21,17 @@ from google import genai
from google.genai import types as genai_types
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 hook_grounding
from clipwright.pipeline.profiles import ProfileError, load_profile
from clipwright.pipeline import profile_prompts
from clipwright.layouts import layout_picker
from clipwright.pipeline import llm_backend
from clipwright.pipeline.clip_selection import (build_transcript_windows, clip_count_targets,
clip_duration_bounds, dedupe_overlapping,
find_hook_start, hook_first_enabled,
score_batches, shortlist_target,
snap_clip_to_words, trim_to_best)
from clipwright.media.ffmpeg_utils import (video_encode_args, cut_clip,
@ -43,6 +48,11 @@ load_dotenv()
# --- Constants ---
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)
# 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.
@ -1300,30 +1310,55 @@ def auto_hook_clip(clip_path, clip, captions=None):
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.
vertical/auto -> 9:16 reframe, square -> 1:1 reframe, horizontal -> keep.
``force_strategy`` (e.g. 'WIDE'/'TRACK') pins every scene's layout — the
clip editor's whole-clip framing override. ``crop_overrides`` positions
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":
return finalize_clip_passthrough(input_video, final_output_video)
aspect = 1.0 if output_format == "square" else ASPECT_RATIO
return process_video_to_vertical(input_video, final_output_video, aspect_ratio=aspect,
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,
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
scene detection and Active Speaker Tracking (MediaPipe).
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
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
# 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()
result = reframe_v2.render(input_video, final_output_video, aspect_ratio,
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")
return result
except Exception as e:
@ -1593,6 +1629,93 @@ def clear_transcript_checkpoint(output_dir):
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"))
@ -1607,6 +1730,57 @@ def clip_render_order(shorts):
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():
try:
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'
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.
words = []
for segment in transcript_result['segments']:
@ -1829,6 +2008,7 @@ def get_viral_clips(transcript_result, video_duration):
video_duration=video_duration, language=language,
min_clips=lo, max_clips=hi,
min_secs=min_secs, max_secs=max_secs,
profile_rules=profile_rules,
windows_json=json.dumps(_payload(ws), ensure_ascii=False))
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,
min_duration=min_secs, max_duration=max_secs)
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)
if len(deduped) < len(shorts):
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).")
parser.add_argument('--transcript', type=str,
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()
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()
def _ensure_dir(path: str) -> str:
@ -2093,7 +2333,7 @@ if __name__ == '__main__':
threading.Thread(target=_early_work, args=(audio_path, audio_duration),
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 not os.environ.get("MAX_SOURCE_MINUTES", "").strip()
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).
from clipwright.pipeline.transcribe_backends import NoAudioError
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
# exact source with the same backend, so reuse its output. Any problem
# with the file falls back to transcribing normally rather than failing.
if args.transcript:
elif args.transcript:
try:
with open(args.transcript, 'r') as f:
transcript = json.load(f)
@ -2250,6 +2503,19 @@ if __name__ == '__main__':
else:
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,
# which is correct (there's no speech to caption).
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
# whichever is current. Each worker writes only its own clip
# 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:
print(f" 🎞️ Clip {i+1} framed")
deliver_path = clip_final_path

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

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

@ -154,7 +154,7 @@ class TestDetailPromptCarriesTheCount:
low, high = clip_count_targets(5)
prompt = gw.DETAIL_PROMPT_TEMPLATE.format(
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 "15 to 60 seconds" in prompt
# The JSON schema example legitimately keeps braces (they are {{ }} in

View file

@ -64,7 +64,7 @@ class TestPromptTemplates:
def test_detail_template_carries_the_band(self):
text = _templates()["DETAIL_PROMPT_TEMPLATE"].format(
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 "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

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