From 2dc1ba1eeaaf756529df717e014979f19bb63cd1 Mon Sep 17 00:00:00 2001 From: pedro-bento Date: Mon, 5 Oct 2026 20:33:56 +0100 Subject: [PATCH] feat/youtube-growth-toolkit (#8) Reviewed-on: https://git.pbento.pt/pedro-bento/clipwright/pulls/8 Co-authored-by: pedro-bento Co-committed-by: pedro-bento --- .gitignore | 1 + Dockerfile | 12 + channels/cseea.json | 30 + channels/pedro.json | 30 + clipwright/api/app.py | 374 ++++++++- clipwright/api/free_tools.py | 59 +- clipwright/integrations/youtube_data.py | 154 ++++ clipwright/layouts/code_layout.py | 909 +++++++++++++++++++++ clipwright/layouts/layout_picker.py | 3 + clipwright/layouts/punch_in.py | 100 ++- clipwright/layouts/reframe_v2.py | 88 +- clipwright/media/thumbnail.py | 246 +++++- clipwright/media/title_validation.py | 170 ++++ clipwright/pipeline/bridge.py | 207 +++++ clipwright/pipeline/clip_selection.py | 184 +++++ clipwright/pipeline/gemini_worker.py | 9 +- clipwright/pipeline/hook_grounding.py | 2 +- clipwright/pipeline/main.py | 289 ++++++- clipwright/pipeline/profile_prompts.py | 125 +++ clipwright/pipeline/profiles.py | 295 +++++++ clipwright/tools/verify_code_layout.py | 169 ++++ dashboard/src/App.jsx | 64 +- dashboard/src/components/BridgeModal.jsx | 331 ++++++++ dashboard/src/components/MediaInput.jsx | 107 ++- dashboard/src/components/ResultCard.jsx | 54 +- docker-compose.yml | 9 + tests/e2e/api/test_handoff_submit.py | 99 +++ tests/e2e/api/test_thumbnail_routes.py | 49 ++ tests/e2e/pipeline/test_handoff_stage.py | 102 +++ tests/e2e/pipeline/test_layout_stage.py | 88 ++ tests/e2e/pipeline/test_thumbnail_stage.py | 4 +- tests/test_bridge.py | 101 +++ tests/test_bridge_endpoint.py | 132 +++ tests/test_channels_endpoint.py | 41 + tests/test_clip_selection.py | 2 +- tests/test_code_layout.py | 231 ++++++ tests/test_generation_controls.py | 2 +- tests/test_handoff.py | 166 ++++ tests/test_handoff_api.py | 177 ++++ tests/test_hook_start.py | 170 ++++ tests/test_layout_picker.py | 3 +- tests/test_profile_prompts.py | 260 ++++++ tests/test_profiles.py | 214 +++++ tests/test_provenance.py | 157 ++++ tests/test_punch_in_beats.py | 93 +++ tests/test_thumbnail_studio.py | 8 +- tests/test_title_validator.py | 316 +++++++ tests/test_youtube_data.py | 130 +++ 48 files changed, 6440 insertions(+), 126 deletions(-) create mode 100644 channels/cseea.json create mode 100644 channels/pedro.json create mode 100644 clipwright/integrations/youtube_data.py create mode 100644 clipwright/layouts/code_layout.py create mode 100644 clipwright/media/title_validation.py create mode 100644 clipwright/pipeline/bridge.py create mode 100644 clipwright/pipeline/profile_prompts.py create mode 100644 clipwright/pipeline/profiles.py create mode 100644 clipwright/tools/verify_code_layout.py create mode 100644 dashboard/src/components/BridgeModal.jsx create mode 100644 tests/e2e/api/test_handoff_submit.py create mode 100644 tests/e2e/pipeline/test_handoff_stage.py create mode 100644 tests/test_bridge.py create mode 100644 tests/test_bridge_endpoint.py create mode 100644 tests/test_channels_endpoint.py create mode 100644 tests/test_code_layout.py create mode 100644 tests/test_handoff.py create mode 100644 tests/test_handoff_api.py create mode 100644 tests/test_hook_start.py create mode 100644 tests/test_profile_prompts.py create mode 100644 tests/test_profiles.py create mode 100644 tests/test_provenance.py create mode 100644 tests/test_punch_in_beats.py create mode 100644 tests/test_title_validator.py create mode 100644 tests/test_youtube_data.py diff --git a/.gitignore b/.gitignore index dc37ef1..982d997 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,7 @@ output/ # Cache dirs .cache/ .config/ +.fontconfig/ .pytest_cache/ .ruff_cache/ diff --git a/Dockerfile b/Dockerfile index a16c400..6ac97f9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -71,6 +71,18 @@ COPY --from=builder /opt/venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" ENV PYTHONUNBUFFERED=1 +# Runtime caches must not land inside the bind-mounted source tree. Compose +# mounts the host repo at /app, and the container's non-root appuser cannot +# write there, so matplotlib/fontconfig logged permission errors and dropped a +# stray .fontconfig (owned by the container's uid) into the repo. Point HOME +# and the disposable caches at writable /tmp; keep the ASR model cache on the +# named volume mounted at HF_HOME (see docker-compose.yml) so it survives +# container recreates. +ENV HOME=/tmp \ + MPLCONFIGDIR=/tmp/.cache/matplotlib \ + YOLO_CONFIG_DIR=/tmp/Ultralytics \ + HF_HOME=/app/.cache/huggingface + # GPU runtime wiring — harmless no-ops on CPU builds / hosts without the # NVIDIA runtime. LD_LIBRARY_PATH points at the pip-installed CUDA libs # (paths simply don't exist in CPU images); DRIVER_CAPABILITIES asks the diff --git a/channels/cseea.json b/channels/cseea.json new file mode 100644 index 0000000..bdfe037 --- /dev/null +++ b/channels/cseea.json @@ -0,0 +1,30 @@ +{ + "name": "cseea", + "language": "en", + "tone": "nostalgic and calm; curious, never hype", + "title_rules": { + "max_chars": 60, + "mobile_chars": 38, + "banned_patterns": ["in this video", "tutorial", "let's play", "how to"], + "keyword_position": "start", + "number_policy": "avoid", + "required_signal": "curiosity", + "banned_openers": ["Exploring", "Building", "Playing", "A look at"] + }, + "hook_patterns": [ + "this shouldn't be possible in Alpha", + "the mechanic Mojang forgot to remove", + "you were never supposed to see this", + "I broke the world in one block" + ], + "hook_style": "visual impossibility at frame 0; show the glitch before any words", + "description_template": "{hook}\n\nFull video: {link}\n\n#minecraft #alpha #retro", + "links": ["https://www.youtube.com/@cseea"], + "thumbnail": { + "role_order": ["curiosity", "emotion", "technical"], + "palette": ["mossy green", "cobblestone grey", "torch orange"], + "presenter_photo": false + }, + "default_postiz_integration_id": null, + "published_video_history": [] +} diff --git a/channels/pedro.json b/channels/pedro.json new file mode 100644 index 0000000..70e0945 --- /dev/null +++ b/channels/pedro.json @@ -0,0 +1,30 @@ +{ + "name": "Pedro Bento", + "language": "en", + "tone": "technical, direct, engineering-focused", + "title_rules": { + "max_chars": 70, + "mobile_chars": 42, + "banned_patterns": ["in this video", "for beginners", "quick tip"], + "keyword_position": "start", + "number_policy": "allow", + "required_signal": "consequence", + "banned_openers": ["Explaining", "Discussing", "Talking about"] + }, + "hook_patterns": [ + "it crashes the moment you resize", + "watch the benchmark number change", + "the bug that survived three rewrites", + "this one syscall cost 40% throughput" + ], + "hook_style": "show the working demo or the bug first, then state the stake in one line", + "description_template": "{hook}\n\nChapters and source: {link}\n\n#c #linux #systems", + "links": ["https://github.com/pbento"], + "thumbnail": { + "role_order": ["technical", "curiosity", "emotion"], + "palette": ["terminal black", "signal amber", "trace red"], + "presenter_photo": true + }, + "default_postiz_integration_id": null, + "published_video_history": [] +} diff --git a/clipwright/api/app.py b/clipwright/api/app.py index 8fb8116..2fb0b7e 100644 --- a/clipwright/api/app.py +++ b/clipwright/api/app.py @@ -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/.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/.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 ``/source_transcript.json`` and a manifest + pointing at it to ``/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, - generate_youtube_description, - api_key, - req.title, - segments, - session.get("language", "en"), - session.get("video_duration", 0) + functools.partial( + generate_youtube_description, + api_key, + req.title, + segments, + session.get("language", "en"), + session.get("video_duration", 0), + profile=profile, + ), ) return {"description": result.get("description", "")} diff --git a/clipwright/api/free_tools.py b/clipwright/api/free_tools.py index 4ff61a3..ff568db 100644 --- a/clipwright/api/free_tools.py +++ b/clipwright/api/free_tools.py @@ -41,6 +41,8 @@ from urllib.parse import parse_qs, urlparse from fastapi import APIRouter, HTTPException, Request from pydantic import BaseModel +from clipwright.media import title_validation + router = APIRouter() # --------------------------------------------------------------------------- # @@ -476,6 +478,7 @@ class MetadataRequest(BaseModel): topic: str keyword: Optional[str] = "" audience: Optional[str] = "" + channel: Optional[str] = None _COMMON_RULES = """ @@ -543,8 +546,13 @@ def _clean(s: str) -> str: return re.sub(r"\s*—\s*", ", ", (s or "")).strip() -def shape_result(mode: str, data: dict) -> dict: - """Validate and tidy the model's JSON into what the page renders.""" +def shape_result(mode: str, data: dict, profile=None) -> dict: + """Validate and tidy the model's JSON into what the page renders. + + For ``titles``, ``profile`` adds the channel's rule checks (PLAN #3) and the + result carries a ``violations`` list so the caller can re-ask once. The + caller pops ``violations`` before returning it to the client. + """ if mode == "titles": items = [] for t in (data.get("titles") or [])[:12]: @@ -555,7 +563,11 @@ def shape_result(mode: str, data: dict) -> dict: items.append({"title": title, "angle": _clean(str(t.get("angle", "")))[:40]}) if not items: raise ValueError("no titles") - return {"titles": items} + return { + "titles": items, + "violations": title_validation.validate_titles( + [i["title"] for i in items], profile), + } if mode == "description": desc = _clean(str(data.get("description", "")))[:5000] if not desc: @@ -576,6 +588,37 @@ def shape_result(mode: str, data: dict) -> dict: return {"tags": tags, "characters": len(",".join(tags))} +def _profile_for_channel(channel): + """Resolve the optional channel field to a Profile (PLAN #3).""" + slug = str(channel or "").strip() + if not slug: + return None + from clipwright.pipeline.profiles import ProfileError, load_profile + try: + return load_profile(slug) + except ProfileError as e: + raise HTTPException(status_code=400, + detail={"code": "bad_channel", "message": str(e)}) + + +def _retry_titles(prompt, candidate, profile): + """One re-ask with the critique; keeps the first attempt if it fails.""" + def validate(c): + return title_validation.validate_titles([t["title"] for t in c["titles"]], profile) + + def retry_once(violations): + try: + data = _generate(prompt + "\n\n" + title_validation.critique_block(violations)) + return shape_result("titles", data, profile) + except Exception as e: # a failed re-ask must not lose the first attempt + print(f"[free_tools] title retry failed: {e}") + return None + + best = title_validation.run_with_validation(lambda: candidate, validate, retry_once) + best.pop("violations", None) + return best + + def _gemini_key(): return os.environ.get("GEMINI_API_KEY", "").strip() or None @@ -631,12 +674,20 @@ async def youtube_metadata(payload: MetadataRequest, request: Request): raise HTTPException(status_code=503, detail={ "code": "not_configured", "message": "This tool needs a Gemini API key on the server."}) _enforce("metadata", request) + profile = _profile_for_channel(payload.channel) prompt = build_prompt(mode, topic.replace("{", "(").replace("}", ")"), keyword, audience) last = None for _ in range(2): try: data = await asyncio.wait_for(asyncio.to_thread(_generate, prompt), timeout=40) - return {"mode": mode, **shape_result(mode, data)} + shaped = shape_result(mode, data, profile) + # Deterministic title QA (PLAN #3): one re-ask if the titles break + # the rules, then keep the better attempt. Never blocks the job. + if mode == "titles" and shaped.get("violations"): + shaped = await asyncio.wait_for( + asyncio.to_thread(_retry_titles, prompt, shaped, profile), timeout=80) + shaped.pop("violations", None) + return {"mode": mode, **shaped} except asyncio.TimeoutError: last = "timeout" break diff --git a/clipwright/integrations/youtube_data.py b/clipwright/integrations/youtube_data.py new file mode 100644 index 0000000..8c08f75 --- /dev/null +++ b/clipwright/integrations/youtube_data.py @@ -0,0 +1,154 @@ +"""Minimal YouTube Data API v3 client -- first comment only (PLAN #6). + +The Shorts "Related video" link and comment pinning are Studio-UI only and are +**not** exposed by any API, so this module deliberately does one thing: post a +top-level comment on a video via ``commentThreads.insert``. Pinning that comment +stays manual. + +Auth is a real-channel OAuth refresh token (service accounts do not work for +this scope). Credentials come from the environment and the integration is +**opt-in**: with any of them missing, :func:`is_configured` is false and no +network call is ever made. Callers must check :func:`is_configured` (or handle +:class:`YoutubeDataError`) before asking for a comment. + +Quota: ``commentThreads.insert`` costs 50 units of the default 10,000/day +project quota (~200 comments/day). That is the whole reason posting is a +deliberate, caller-triggered action and never automatic. + +Blocking, like ``postiz.py``: call through ``asyncio.to_thread`` from async +handlers. Every function accepts an optional pre-built ``httpx.Client`` so tests +can inject a ``httpx.MockTransport`` and no live OAuth is ever needed. +""" + +from __future__ import annotations + +import os +from typing import Any, Dict, Optional + +import httpx + +TOKEN_URI = "https://oauth2.googleapis.com/token" +COMMENT_THREADS_URL = "https://www.googleapis.com/youtube/v3/commentThreads" +# Required by insert (the comment posting endpoint). Read-only analytics use a +# different scope; this module never reads. +SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl" + +# Environment variable names, kept as constants so the API layer can name them +# in its "not configured" message without duplicating strings. +CLIENT_ID_ENV = "YOUTUBE_OAUTH_CLIENT_ID" +CLIENT_SECRET_ENV = "YOUTUBE_OAUTH_CLIENT_SECRET" +REFRESH_TOKEN_ENV = "YOUTUBE_OAUTH_REFRESH_TOKEN" +TOKEN_URI_ENV = "YOUTUBE_OAUTH_TOKEN_URI" + + +class YoutubeDataError(Exception): + """A missing config or non-2xx response from the YouTube Data API. + + Carries the status and body so the FastAPI layer can translate it into the + same status/detail it would have surfaced otherwise. + """ + + def __init__(self, status_code: int, detail: str): + super().__init__(detail) + self.status_code = status_code + self.detail = detail + + +def _env(name: str, default: Optional[str] = None) -> Optional[str]: + value = os.environ.get(name) + if value is None: + return default + value = value.strip() + return value or default + + +def credentials() -> Dict[str, Optional[str]]: + """The OAuth credentials read from the environment (values may be None).""" + return { + "client_id": _env(CLIENT_ID_ENV), + "client_secret": _env(CLIENT_SECRET_ENV), + "refresh_token": _env(REFRESH_TOKEN_ENV), + "token_uri": _env(TOKEN_URI_ENV, TOKEN_URI), + } + + +def is_configured() -> bool: + """True when a refresh-token flow can run. False = no-op, never called.""" + creds = credentials() + return all(creds[key] for key in ("client_id", "client_secret", "refresh_token")) + + +def _access_token(client: httpx.Client, creds: Dict[str, Optional[str]]) -> str: + resp = client.post(str(creds["token_uri"]), data={ + "client_id": creds["client_id"], + "client_secret": creds["client_secret"], + "refresh_token": creds["refresh_token"], + "grant_type": "refresh_token", + }) + if resp.status_code != 200: + raise YoutubeDataError( + 502, + f"YouTube OAuth token refresh failed: {(resp.text or '')[:300]}", + ) + try: + token = (resp.json() or {}).get("access_token") + except ValueError: + token = None + if not token: + raise YoutubeDataError(502, "YouTube OAuth token refresh returned no access_token") + return token + + +def post_first_comment(video_id: str, text: str, timeout: float = 60.0, + client: Optional[httpx.Client] = None) -> Dict[str, Any]: + """Post ``text`` as a top-level comment on ``video_id``. + + Returns the API's ``commentThreads.insert`` response (id + snippet). + + Raises :class:`YoutubeDataError` when unconfigured, given bad input, or when + YouTube rejects the insert. ``client`` is the test seam; pass an + ``httpx.Client`` built with a ``MockTransport`` to exercise this offline. + """ + if not video_id or not str(video_id).strip(): + raise YoutubeDataError(400, "video_id is required") + if not text or not str(text).strip(): + raise YoutubeDataError(400, "comment text is required") + if not is_configured(): + raise YoutubeDataError( + 400, + "YouTube Data API is not configured; set " + f"{CLIENT_ID_ENV}, {CLIENT_SECRET_ENV} and {REFRESH_TOKEN_ENV}", + ) + + owns_client = client is None + client = client or httpx.Client(timeout=timeout) + try: + token = _access_token(client, credentials()) + resp = client.post( + COMMENT_THREADS_URL, + params={"part": "snippet"}, + headers={"Authorization": f"Bearer {token}"}, + json={"snippet": { + "videoId": str(video_id).strip(), + "topLevelComment": { + "snippet": {"textOriginal": str(text)}, + }, + }}, + ) + finally: + if owns_client: + client.close() + + if resp.status_code not in (200, 201): + # 4xx are the caller's (invalid video / scope); 5xx become 502 so the + # API layer does not claim the upstream is down with a gateway code + # that came from YouTube, not this server. + status = resp.status_code if resp.status_code < 500 else 502 + raise YoutubeDataError( + status, + f"YouTube commentThreads.insert failed: {(resp.text or '')[:300]}", + ) + try: + return resp.json() or {} + except ValueError: + return {} diff --git a/clipwright/layouts/code_layout.py b/clipwright/layouts/code_layout.py new file mode 100644 index 0000000..ac2f424 --- /dev/null +++ b/clipwright/layouts/code_layout.py @@ -0,0 +1,909 @@ +"""CODE/TERMINAL vertical layout: an IDE or terminal recording in 9:16. + +The case every screen layout here handles badly: a maximized 1440p editor or a +terminal window. The existing SCREENCAST layout treats it as "content over a +presenter", which on a code recording means the output is the whole 1440p frame +shrunk to a 608px strip — 24px of glyph height at best, unreadable on a phone. + +What a code recording actually needs is the opposite trade. The viewer has to +read characters, so the *pane* is cropped to one column of code and scaled up to +fill the width, with the source's blur as decorative filler above and below, and +the bottom ~15% left clear for captions. When the pane is taller than the output +band, a crop window has to follow the active line (a `sendcmd` pan) so the line +being typed stays on screen. + +Design, following the ``camera_inset`` pattern: + + - module ``ENABLED`` read from ``CODE_LAYOUT`` (off by default); + - ``detect_code_pane`` -> geometry (a self-contained edge/row-column detector, + like ``split_layout.detect_split_scenes``: no ``content_ranges`` dead wire); + - pure geometry helpers (``pane_from_projections``, ``stable_pane``, + ``fit_window``, ``follow_sendcmd_lines``) so the decisions are unit-testable + without OpenCV; + - ``code_filtergraph`` -> crop -> scale -> overlay on a blurred backdrop. + +Everything tunable is an env-overridable constant. The thresholds were set from +first principles and *must* be calibrated against a real 1440p corpus with +``clipwright/tools/verify_code_layout.py`` before the layout is enabled by +default. + +Import-time cost is ``numpy`` only; ``cv2`` is imported lazily inside the frame +functions so the unit suite (which has no OpenCV) still collects this module. +""" +import os + +import numpy as np + +from clipwright.media.ffmpeg_utils import blurred_backdrop + +# Off by default: a wrong CODE crop shows a wall of clipped glyphs, which is a +# worse failure than leaving a code clip on the TRACK/WIDE default. +ENABLED = os.environ.get("CODE_LAYOUT", "0") == "1" + +# --------------------------------------------------------------------------- +# Env-overridable tuning. See clipwright/tools/verify_code_layout.py for the +# corpus pass that produces real numbers for these; the defaults are estimates. +# --------------------------------------------------------------------------- + +# Pan the crop window to keep the active line visible on a tall pane. +FOLLOW_ENABLED = os.environ.get("CODE_FOLLOW", "1") == "1" + +# Extra zoom on top of "fit the pane width to the output width". 1.0 keeps the +# whole pane width; >1 crops a narrower column and scales it up (bigger glyphs). +ZOOM = float(os.environ.get("CODE_ZOOM", "1.0")) + +# Minimum horizontal scale (out_w / pane_w). Below this the pane is being +# downscaled so far that the text stops being readable, and the caller should +# fall back to SCREENCAST/WIDE. At 1440p maximized, out_w/pane_w == 1080/1440 == +# 0.75 exactly, so a maximized editor sits on the boundary and a maximized +# ultrawide falls through. +MIN_SCALE = float(os.environ.get("CODE_MIN_SCALE", "0.75")) + +# Face/camera band height, as a fraction of out_h, when a cam_box is supplied. +CAMERA_BAND_RATIO = float(os.environ.get("CODE_CAMERA_BAND", "0.18")) + +# Bottom band reserved for captions, as a fraction of out_h. +CAPTION_BAND_RATIO = float(os.environ.get("CODE_CAPTION_BAND", "0.15")) + +# Pane gates, as a fraction of the frame. A corner panel is not a code pane. +PANE_MIN_WIDTH_FRAC = float(os.environ.get("CODE_PANE_MIN_WIDTH", "0.35")) +PANE_MIN_HEIGHT_FRAC = float(os.environ.get("CODE_PANE_MIN_HEIGHT", "0.25")) + +# Edge-density floor inside the pane (fraction of pixels above the Sobel +# threshold). Flat wallpapers and photos fall below it. +EDGE_DENSITY_FLOOR = float(os.environ.get("CODE_EDGE_DENSITY", "0.02")) + +# Temporal stability: the pane centre must stay within this fraction of the +# frame across samples, for at least this fraction of them. +STABILITY_TOLERANCE = float(os.environ.get("CODE_STABILITY_TOLERANCE", "0.04")) +STABILITY_MIN_FRAC = float(os.environ.get("CODE_STABILITY_FRAC", "0.6")) + +# Detection runs on a copy at most this wide. Sobel/close is O(pixels) and the +# pane geometry does not need full resolution. +DETECT_MAX_WIDTH = int(os.environ.get("CODE_DETECT_WIDTH", "960")) + +# Wide-short morphological close: joins glyphs into horizontal line runs +# without merging adjacent text lines (which a square kernel does). +CLOSE_KERNEL = (35, 3) + +# Fraction of the projection max that counts as pane edge mass. +PROJ_THRESHOLD_RATIO = float(os.environ.get("CODE_PROJ_THRESHOLD", "0.15")) + +# Below this scaled Sobel magnitude a frame contributes no edge map. +SOBEL_FLOOR = float(os.environ.get("CODE_SOBEL_FLOOR", "8.0")) +SOBEL_RATIO = 0.15 + +# Active-line tracking. +ACTIVE_MAX_WIDTH = int(os.environ.get("CODE_ACTIVE_WIDTH", "480")) +ACTIVE_BAND_FRAC = 0.20 +ACTIVE_MIN_CONCENTRATION = float( + os.environ.get("CODE_ACTIVE_CONCENTRATION", "0.35")) +ACTIVE_MIN_MASS = float(os.environ.get("CODE_ACTIVE_MASS", "1500")) + +# Editor classification: syntax highlighting raises chroma variance above a +# plain terminal's. +EDITOR_SAT_STD = float(os.environ.get("CODE_EDITOR_SAT_STD", "28")) +GUTTER_FRACTION = 0.12 + +# IDE chrome masking. A maximized editor's window is the whole 2560px of a 1440p +# source, so a whole-window pane scales at 1080/2560 ~= 0.42 and trips +# MIN_SCALE. What we want is the TEXT COLUMN: the activity bar and sidebar sit +# in the left margin and the minimap in the right, each separated from the code +# by a sustained blank border. The detector searches within these margins for +# that blank run and cuts there; with no chrome (a bare terminal) there is no +# run and the full width is kept. Widths vary by theme and zoom — tune +# CODE_CHROME_* and CODE_TEXT_* from tools/verify_code_layout.py. +CHROME_LEFT_FRAC = float(os.environ.get("CODE_CHROME_LEFT", "0.22")) +CHROME_RIGHT_FRAC = float(os.environ.get("CODE_CHROME_RIGHT", "0.10")) +CHROME_BOTTOM_FRAC = float(os.environ.get("CODE_CHROME_BOTTOM", "0.03")) +# A "gap" is a sustained run of columns below this share of the text max. +GAP_FRAC = float(os.environ.get("CODE_GAP_FRAC", "0.08")) +GAP_PX = int(os.environ.get("CODE_GAP_PX", "4")) +TEXT_CORE_FRAC = float(os.environ.get("CODE_TEXT_CORE", "0.35")) +TEXT_MIN_WIDTH_FRAC = float(os.environ.get("CODE_TEXT_MIN_WIDTH", "0.2")) + +# Per-scene verification: share of frames sampled inside the pane that must +# still read as code for the scene to keep CODE (otherwise its other verdict +# stands). A cutaway to the facecam fails the texture/palette checks. +SCENE_CODE_FRAC = float(os.environ.get("CODE_SCENE_FRAC", "0.5")) + + +# --------------------------------------------------------------------------- +# Pure geometry (no cv2): projections -> pane, stability, band layout, sendcmd. +# --------------------------------------------------------------------------- + +def _extent(projection, threshold): + """First/last index above ``threshold`` (end exclusive), or None.""" + idx = np.flatnonzero(np.asarray(projection, dtype=float) > threshold) + if idx.size == 0: + return None + return int(idx[0]), int(idx[-1]) + 1 + + +def pane_from_projections(row_proj, col_proj, frame_w, frame_h, + min_width_frac=PANE_MIN_WIDTH_FRAC, + min_height_frac=PANE_MIN_HEIGHT_FRAC, + threshold_ratio=PROJ_THRESHOLD_RATIO): + """Locate the code pane from 1-D row/column edge projections. + + ``row_proj`` is per-row edge mass (length = pane-space height) and + ``col_proj`` per-column. The pane is the bounding extent of edge mass above + a fraction of each projection's own max: text lines are many separated rows + of mass, so a "longest contiguous run" would lock onto a single line. The + extent is in the same coordinate space as ``frame_w``/``frame_h`` (detection + passes the downscaled size; the fractions are scale-invariant). + + Returns ``(x, y, w, h)`` or None when the box is missing or fails either + size gate. + """ + rows = np.asarray(row_proj, dtype=float) + cols = np.asarray(col_proj, dtype=float) + if rows.size == 0 or cols.size == 0: + return None + if rows.max() <= 0 or cols.max() <= 0: + return None + ry = _extent(rows, threshold_ratio * rows.max()) + cx = _extent(cols, threshold_ratio * cols.max()) + if ry is None or cx is None: + return None + y0, y1 = ry + x0, x1 = cx + w, h = x1 - x0, y1 - y0 + if w < min_width_frac * frame_w or h < min_height_frac * frame_h: + return None + return (x0, y0, w, h) + + +def _smooth(values, window=9): + v = np.asarray(values, dtype=float) + if window <= 1 or v.size < window: + return v + kernel = np.ones(window, dtype=float) / window + return np.convolve(v, kernel, mode="same") + + +def _gaps(below, gap_px): + """(start, end) of every sustained True run in a boolean array.""" + out = [] + start = None + for i, flag in enumerate(below): + if flag and start is None: + start = i + elif not flag and start is not None: + if i - start >= gap_px: + out.append((start, i)) + start = None + if start is not None and len(below) - start >= gap_px: + out.append((start, len(below))) + return out + + +def text_column_extent(col_proj, frame_w, left_skip_frac=CHROME_LEFT_FRAC, + right_skip_frac=CHROME_RIGHT_FRAC, + core_frac=TEXT_CORE_FRAC, + min_width_frac=TEXT_MIN_WIDTH_FRAC, + gap_frac=GAP_FRAC, gap_px=GAP_PX, smooth=9): + """(x0, x1) of the editor text column, with IDE chrome cut off. + + ``col_proj`` is per-column edge mass. The whole extent of edge mass is + first-to-last above ``core_frac`` of the max (text fills nearly every + column across many lines, so a longest-run would lock onto one block). The + left and right margins are then searched for a sustained blank border — the + gap between the sidebar and the code, and between the code and the + minimap — and the extent is cut at the innermost one. A bare terminal has + no such border and keeps its full width. Returns None when no run clears + ``min_width_frac``. + """ + cols = _smooth(col_proj, smooth) + if cols.size == 0: + return None + top = float(cols.max()) + if top <= 0: + return None + core = cols > core_frac * top + if not core.any(): + return None + first = int(np.argmax(core)) + last = int(len(core) - np.argmax(core[::-1])) + + thr = gap_frac * top + x0 = first + window = cols[first:first + int(round(left_skip_frac * frame_w))] + gaps = _gaps(window < thr, max(2, gap_px)) + if gaps: + x0 = first + gaps[-1][1] + + x1 = last + rstart = max(x0, last - int(round(right_skip_frac * frame_w))) + window = cols[rstart:last] + gaps = _gaps(window < thr, max(2, gap_px)) + if gaps: + x1 = rstart + gaps[-1][0] + + if x1 - x0 < min_width_frac * frame_w: + return None + return x0, x1 + + +def clamp_pane_width(pane, max_width, anchor="left"): + """Narrow a pane to at most ``max_width`` columns. + + Used when the text column is still wider than the readable scale allows + (1080 / MIN_SCALE ~= 1440 on a 1440p source): code is left-aligned, so + keeping the left edge keeps indentation and line starts. Returns an even + ``(x, y, w, h)`` tuple. + """ + x, y, w, h = _pane_box(pane) + max_width = int(max_width) - (int(max_width) % 2) + if max_width < 2: + max_width = 2 + if w <= max_width: + return (x, y, w, h) + nx = x + (w - max_width) // 2 if anchor == "center" else x + nx = max(0, nx - (nx % 2)) + return (nx, y, max_width, h) + + +def _stable_members(boxes, frame_w, frame_h, tolerance): + arr = np.asarray(boxes, dtype=float) + cx = arr[:, 0] + arr[:, 2] / 2.0 + cy = arr[:, 1] + arr[:, 3] / 2.0 + mid_x, mid_y = float(np.median(cx)), float(np.median(cy)) + close = ((np.abs(cx - mid_x) <= tolerance * frame_w) + & (np.abs(cy - mid_y) <= tolerance * frame_h)) + return arr, close + + +def stable_pane(boxes, frame_w, frame_h, tolerance=STABILITY_TOLERANCE, + min_frac=STABILITY_MIN_FRAC): + """Median box over the samples that agree, or None. + + A pane that jumps around the screen is a moving camera or a slideshow, not a + fixed editor window; clustering around the median tolerates one stray sample + without tolerating real movement. + """ + if not boxes: + return None + arr, close = _stable_members(boxes, frame_w, frame_h, tolerance) + if int(close.sum()) < max(2, int(round(min_frac * len(boxes)))): + return None + return tuple(int(round(v)) for v in np.median(arr[close], axis=0)) + + +def stability_fraction(boxes, frame_w, frame_h, tolerance=STABILITY_TOLERANCE): + """Fraction of samples whose centre agrees with the median.""" + if not boxes: + return 0.0 + _, close = _stable_members(boxes, frame_w, frame_h, tolerance) + return float(close.mean()) if close.size else 0.0 + + +def edge_density(mask, box): + """Fraction of set pixels inside ``box`` (mask may be 0/1 or 0/255).""" + x, y, w, h = (int(v) for v in box[:4]) + m = np.asarray(mask) + sub = m[max(0, y):y + h, max(0, x):x + w] + if sub.size == 0: + return 0.0 + scale = 255.0 if sub.max() > 1 else 1.0 + return float(sub.mean()) / scale + + +def code_bands(out_h, caption_ratio=None): + """(content_h, caption_h): even, positive, and summing to ``out_h``.""" + ratio = CAPTION_BAND_RATIO if caption_ratio is None else caption_ratio + caption_h = int(round(out_h * ratio)) + caption_h -= caption_h % 2 + caption_h = max(2, min(caption_h, out_h - 2)) + content_h = out_h - caption_h + return content_h, caption_h + + +def fit_window(pane_h, scale, band_h): + """(crop_h, scaled_h, needs_follow) for a pane of ``pane_h`` at ``scale``. + + ``crop_h`` is the source window height, ``scaled_h`` its height after + scaling, both even and clamped so ``scaled_h <= band_h``. ``needs_follow`` + is True when the pane is taller than the band and only a window can fit. + """ + pane_h = max(2, int(pane_h)) + if scale <= 0: + return None + full_scaled = pane_h * scale + if full_scaled <= band_h: + scaled_h = int(round(full_scaled)) + scaled_h += scaled_h % 2 + scaled_h = max(2, min(scaled_h, band_h)) + crop_h = pane_h - (pane_h % 2) + return max(2, crop_h), scaled_h, False + crop_h = int(round(band_h / scale)) + crop_h += crop_h % 2 + crop_h = max(2, min(crop_h, pane_h - (pane_h % 2))) + scaled_h = band_h - (band_h % 2) + return crop_h, max(2, scaled_h), True + + +def follow_sendcmd_lines(follow, pane_y, window_h, pane_h, start=0.0, + target="crop@c"): + """sendcmd lines panning a crop window to the active line. + + ``follow`` is ``[(timestamp, source_y), ...]`` where ``timestamp`` is in the + source's clock; ``start`` is the segment start, subtracted so the emitted + timestamps are relative to the segment (the render seeks per scene). Only + change-points are emitted: ``y`` is clamped to the pane and deduped. + """ + lines = [] + prev = None + lo = int(pane_y) + hi = max(lo, int(pane_y + pane_h - window_h)) + for t, y in follow: + rel = float(t) - float(start) + if rel < 0: + continue + top = int(round(float(y) - window_h / 2.0)) + top = max(lo, min(top, hi)) + top -= top % 2 + if top == prev: + continue + lines.append(f"{rel:.4f} {target} y {top};") + prev = top + return lines + + +def _pane_box(pane): + if isinstance(pane, dict): + return (int(pane["x"]), int(pane["y"]), int(pane["w"]), int(pane["h"])) + return tuple(int(v) for v in pane[:4]) + + +def code_filtergraph(pane, out_w, out_h, follow=None, cam_box=None, + min_scale=MIN_SCALE, caption_ratio=None, zoom=None): + """Crop the code pane, scale it to ``out_w``, overlay on a blurred backdrop. + + ``pane`` is an ``(x, y, w, h)`` tuple or a ``detect_code_pane`` dict in + SOURCE coordinates. ``follow`` is a segment-relative + ``[(t, source_y), ...]`` series from ``active_line_series``; it produces a + ``sendcmd`` pan when the pane is taller than the content band. ``cam_box`` + optionally overlays a face in the caption band. + + Returns the filtergraph string ending in ``[v]``, or None when + ``out_w / pane_w < min_scale`` so the caller can fall back to + SCREENCAST/WIDE. + """ + x, y, w, h = _pane_box(pane) + x = max(0, x - (x % 2)) + y = max(0, y - (y % 2)) + w = max(2, w - (w % 2)) + h = max(2, h - (h % 2)) + + fit = out_w / float(w) + if fit < min_scale: + return None + + z = ZOOM if zoom is None else zoom + scale = fit * max(0.1, float(z)) + if scale <= 0: + return None + + content_h, caption_h = code_bands(out_h, caption_ratio) + + # Horizontal crop window: at zoom 1 this is the whole pane width. + crop_w = int(round(out_w / scale)) + crop_w += crop_w % 2 + crop_w = max(2, min(crop_w, w)) + crop_x = x + (w - crop_w) // 2 + crop_x = max(0, crop_x - (crop_x % 2)) + + fitted = fit_window(h, scale, content_h) + if fitted is None: + return None + crop_h, scaled_h, needs_follow = fitted + y_off = max(0, (content_h - scaled_h) // 2) + + window_top = None + if needs_follow: + window_top = y + (h - crop_h) // 2 + if follow: + window_top = int(round(float(follow[0][1]) - crop_h / 2.0)) + window_top = max(y, min(window_top, y + h - crop_h)) + window_top -= window_top % 2 + + if needs_follow and follow: + lines = follow_sendcmd_lines(follow, y, crop_h, h, start=0.0) + else: + lines = [] + + if lines: + # Each line is already ';'-terminated; concatenating avoids the empty + # command a second separator would produce. + commands = "".join(lines) + fg = (f"sendcmd=c='{commands}'," + f"crop@c=w={crop_w}:h={crop_h}:x={crop_x}:y={window_top}," + f"scale={out_w}:{scaled_h}[code]") + else: + static_y = (window_top if window_top is not None + else y + (h - crop_h) // 2) + static_y = max(y, min(static_y, y + h - crop_h)) + static_y -= static_y % 2 + fg = (f"crop=w={crop_w}:h={crop_h}:x={crop_x}:y={static_y}," + f"scale={out_w}:{scaled_h}[code]") + + parts = [] + if cam_box is not None: + cx, cy, cw, ch = _pane_box(cam_box) + cx = max(0, cx - (cx % 2)) + cy = max(0, cy - (cy % 2)) + cw = max(2, cw - (cw % 2)) + ch = max(2, ch - (ch % 2)) + cam_h = int(round(out_h * CAMERA_BAND_RATIO)) + cam_h -= cam_h % 2 + cam_h = max(2, min(cam_h, caption_h)) + parts.append("[0:v]split=3[bga][fga][cama];") + parts.append(f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];") + parts.append(f"[fga]{fg};") + parts.append(f"[cama]crop=w={cw}:h={ch}:x={cx}:y={cy}," + f"scale={out_w}:{cam_h}[cam];") + parts.append(f"[bg][code]overlay=x=0:y={y_off}[withcode];") + parts.append(f"[withcode][cam]overlay=x=0:y={out_h - caption_h}," + f"setsar=1[v]") + else: + parts.append("[0:v]split=2[bga][fga];") + parts.append(f"[bga]{blurred_backdrop(out_w, out_h, 12)}[bg];") + parts.append(f"[fga]{fg};") + parts.append(f"[bg][code]overlay=x=0:y={y_off},setsar=1[v]") + return "".join(parts) + + +# --------------------------------------------------------------------------- +# OpenCV detection (lazy import). +# --------------------------------------------------------------------------- + +def _downscale(frame, max_width): + import cv2 + h, w = frame.shape[:2] + if w <= max_width: + return frame + factor = max_width / float(w) + return cv2.resize(frame, (max_width, max(2, int(round(h * factor)))), + interpolation=cv2.INTER_AREA) + + +def _edge_maps(frame, max_width=DETECT_MAX_WIDTH): + """Sobel edge mask + wide-short close + row/column projections. + + Returns a dict with the mask, closed mask, projections and the working + dimensions, or None when the frame has no gradient (black/frozen). + """ + import cv2 + small = _downscale(frame, max_width) + gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY) + gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3) + gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3) + mag = cv2.magnitude(gx, gy) + top = float(mag.max()) + if top <= 1e-6: + return None + threshold = max(SOBEL_FLOOR, SOBEL_RATIO * top) + mask = (mag > threshold).astype(np.uint8) * 255 + kernel = cv2.getStructuringElement(cv2.MORPH_RECT, CLOSE_KERNEL) + closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) + return { + "mask": mask, + "closed": closed, + "row_proj": closed.sum(axis=1).astype(np.float64), + "col_proj": closed.sum(axis=0).astype(np.float64), + # The close joins glyphs into line runs, which is what the row + # projection needs — but it also bridges the blank IDE chrome borders, + # so the column projection for TEXT-COLUMN masking comes from the RAW + # mask, where the border survives. + "col_proj_raw": mask.sum(axis=0).astype(np.float64), + "w": small.shape[1], + "h": small.shape[0], + } + + +def _classify_pane(frame, box): + """Editor vs terminal. Defaults to editor when the signal is weak. + + An editor shows a left gutter of stable digit rows (line numbers) and + syntax highlighting raises the crop's saturation variance. A terminal has + neither: text starts at the left margin and is mostly one foreground colour. + """ + import cv2 + x, y, w, h = (int(v) for v in box) + crop = frame[max(0, y):y + h, max(0, x):x + w] + if crop.size == 0: + return "editor" + hsv = cv2.cvtColor(crop, cv2.COLOR_BGR2HSV) + sat_std = float(hsv[:, :, 1].std()) + + gutter_w = max(4, int(w * GUTTER_FRACTION)) + gutter = crop[:, :gutter_w] + gg = cv2.cvtColor(gutter, cv2.COLOR_BGR2GRAY) + gx = np.abs(cv2.Sobel(gg, cv2.CV_32F, 1, 0, ksize=3)) + per_col = gx.sum(axis=0) + total = float(per_col.sum()) + 1e-6 + gutter_peak = float(per_col.max() / total) if per_col.size else 0.0 + + if sat_std >= EDITOR_SAT_STD and gutter_peak > 0.08: + return "editor" + if sat_std < EDITOR_SAT_STD and gutter_peak <= 0.08: + return "terminal" + return "editor" + + +def detect_code_pane(video_path, samples=12): + """Median code pane across sampled frames, or None. + + Pipeline per sample: downscale to <= DETECT_MAX_WIDTH, Sobel magnitude mask, + wide-short morphological close (joins glyphs into line runs), row/column + projection -> bounding pane. Gates: pane width/height fractions, in-pane + edge-density floor, and temporal stability of the pane centre. + + Returns ``{"x", "y", "w", "h", "mode", "confidence", "frame_w", + "frame_h"}`` in source coordinates, or None meaning "use another layout". + """ + if not ENABLED: + return None + try: + import cv2 + except ImportError: + return None + + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + return None + total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + if total <= 0 or frame_w <= 0 or frame_h <= 0: + cap.release() + return None + + n = max(2, int(samples)) + boxes = [] + densities = [] + votes = {"editor": 0, "terminal": 0} + try: + for i in range(n): + cap.set(cv2.CAP_PROP_POS_FRAMES, int(i * total / n)) + ok, frame = cap.read() + if not ok: + continue + maps = _edge_maps(frame) + if maps is None: + continue + det_box = pane_from_projections( + maps["row_proj"], maps["col_proj"], maps["w"], maps["h"]) + if det_box is None: + continue + # The plain projection returns the whole window; cut it down to the + # text column so a maximized 1440p editor does not scale at 0.42. + # Raw projection: the morphological close would bridge the chrome + # borders this is looking for. + text_cols = text_column_extent(maps["col_proj_raw"], maps["w"]) + if text_cols is not None: + x0, x1 = text_cols + else: + x0, x1 = det_box[0], det_box[0] + det_box[2] + y0 = det_box[1] + y1 = det_box[1] + det_box[3] + # Shave the status bar / window border off the bottom. + y1 -= int(round(CHROME_BOTTOM_FRAC * (y1 - y0))) + w, h = x1 - x0, y1 - y0 + if (w < PANE_MIN_WIDTH_FRAC * maps["w"] + or h < PANE_MIN_HEIGHT_FRAC * maps["h"]): + continue + det_box = (x0, y0, w, h) + density = edge_density(maps["closed"], det_box) + if density < EDGE_DENSITY_FLOOR: + continue + sx = frame_w / float(maps["w"]) + sy = frame_h / float(maps["h"]) + box = (int(round(det_box[0] * sx)), int(round(det_box[1] * sy)), + int(round(det_box[2] * sx)), int(round(det_box[3] * sy))) + boxes.append(box) + densities.append(density) + votes[_classify_pane(frame, box)] += 1 + finally: + cap.release() + + if len(boxes) < 2: + return None + stable = stable_pane(boxes, frame_w, frame_h) + if stable is None: + return None + x, y, w, h = stable + if w < PANE_MIN_WIDTH_FRAC * frame_w or h < PANE_MIN_HEIGHT_FRAC * frame_h: + return None + + mode = "editor" if votes["editor"] >= votes["terminal"] else "terminal" + stable_frac = stability_fraction(boxes, frame_w, frame_h) + density = float(np.mean(densities)) if densities else 0.0 + confidence = max(0.0, min(1.0, 0.6 * stable_frac + + 0.4 * min(1.0, density / (4 * EDGE_DENSITY_FLOOR)))) + return {"x": x, "y": y, "w": w, "h": h, "mode": mode, + "confidence": confidence, "frame_w": frame_w, "frame_h": frame_h} + + +def _active_point(row_mass, total, band_frac=ACTIVE_BAND_FRAC, + min_concentration=ACTIVE_MIN_CONCENTRATION): + """(normalised centroid, concentration, mass) of the top-mass row band. + + The centroid is the mass-weighted centre of the busiest ``band_frac`` of + rows, normalised to 0..1 over the region. ``concentration`` is that band's + share of all changed pixels: a caret or highlighted line is concentrated, a + whole-screen redraw is not. + """ + n = len(row_mass) + if n == 0 or total <= 0: + return None + k = max(1, int(round(n * band_frac))) + order = np.argsort(row_mass)[-k:] + band_mass = float(row_mass[order].sum()) + if band_mass <= 0: + return None + concentration = band_mass / float(total) + if concentration < min_concentration: + return None + idx = order.astype(float) + cy = float((idx * row_mass[order]).sum() / band_mass) + return (cy / (n - 1) if n > 1 else 0.0), concentration, band_mass + + +def _median_smooth(values, window=3): + values = np.asarray(values, dtype=float) + if window <= 1 or len(values) < window: + return values + half = window // 2 + out = values.copy() + for i in range(len(values)): + lo = max(0, i - half) + hi = min(len(values), i + half + 1) + out[i] = np.median(values[lo:hi]) + return out + + +def active_line_series(video_path, pane, start, end, sample_fps=2.0): + """Track the active line (caret/current-line highlight) over a range. + + Low-res decode at ``sample_fps``; ``absdiff`` between consecutive samples + masked to the pane; per-row changed mass; the top-mass band's centroid is + kept only when it concentrates >= ``ACTIVE_MIN_CONCENTRATION`` of the change + and the band mass clears the floor. The y series is median-smoothed. + + Returns ``[(timestamp, source_y), ...]`` in the source's absolute clock (the + caller subtracts the segment start when building sendcmd lines), or None + when fewer than three reliable points are found. + """ + if not ENABLED or not FOLLOW_ENABLED: + return None + try: + import cv2 + except ImportError: + return None + if end <= start: + return None + + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + return None + frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + if frame_w <= 0 or frame_h <= 0: + cap.release() + return None + x, y, w, h = _pane_box(pane) + if w <= 0 or h <= 0: + cap.release() + return None + + step = 1.0 / max(0.1, float(sample_fps)) + points = [] + prev_region = None + try: + t = float(start) + while t <= end + 1e-6: + cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000.0) + ok, frame = cap.read() + if not ok: + break + small = _downscale(frame, ACTIVE_MAX_WIDTH) + sw, sh = small.shape[1], small.shape[0] + rx = int(round(x * sw / float(frame_w))) + ry = int(round(y * sh / float(frame_h))) + rw = max(2, int(round(w * sw / float(frame_w)))) + rh = max(2, int(round(h * sh / float(frame_h)))) + rx = max(0, min(rx, sw - 2)) + ry = max(0, min(ry, sh - 2)) + rw = max(2, min(rw, sw - rx)) + rh = max(2, min(rh, sh - ry)) + region = small[ry:ry + rh, rx:rx + rw] + if prev_region is not None and prev_region.shape == region.shape: + diff = cv2.absdiff(region, prev_region) + gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) + row_mass = gray.sum(axis=1).astype(np.float64) + total = float(row_mass.sum()) + if total >= ACTIVE_MIN_MASS: + point = _active_point(row_mass, total) + if point is not None: + points.append((t, y + point[0] * h)) + prev_region = region + t += step + finally: + cap.release() + + if len(points) < 3: + return None + ys = _median_smooth([p[1] for p in points], 3) + return [(float(ts), float(yy)) for (ts, _), yy in zip(points, ys)] + + +def _regular_rows(row_proj, min_period=6, max_period=60, min_peak=0.25): + """True when the row projection has a periodic peak (monospace line pitch). + + Autocorrelation of the mean-subtracted projection; a peak in the plausible + line-height band means evenly spaced text lines rather than prose or a UI. + """ + v = np.asarray(row_proj, dtype=float) + if v.size < min_period + 2: + return False + v = v - v.mean() + denom = float((v * v).sum()) + if denom <= 0: + return False + ac = np.correlate(v, v, mode="full")[len(v) - 1:] + ac = ac / denom + hi = min(max_period, len(ac) - 1) + if hi <= min_period: + return False + return float(ac[min_period:hi + 1].max()) >= min_peak + + +def _texture_ok(maps): + """Edge-density floor + monospace row regularity on an edge-map dict.""" + density = edge_density(maps["closed"], (0, 0, maps["w"], maps["h"])) + if density < EDGE_DENSITY_FLOOR: + return False + return _regular_rows(maps["row_proj"]) + + +def _palette_ok(crop): + """Editor/terminal palette: dark background or mostly monochrome.""" + hsv = _hsv(crop) + sat_std = float(hsv[:, :, 1].std()) + dark = float((hsv[:, :, 2] < 102).mean()) + return bool(dark >= 0.35 or sat_std <= 45.0) + + +def frame_shows_code(frame, pane): + """True when the pane region of THIS frame still reads as code. + + Text density (edge-density floor + monospace row regularity) plus the + editor/terminal palette. A facecam cutaway puts skin/room inside the pane + rectangle, which fails both the row pitch and the dark/monochrome palette. + """ + try: + import cv2 # noqa: F401 + except ImportError: + return False + x, y, w, h = _pane_box(pane) + frame_h, frame_w = frame.shape[:2] + x0 = max(0, min(x, frame_w - 2)) + y0 = max(0, min(y, frame_h - 2)) + x1 = max(x0 + 2, min(x + w, frame_w)) + y1 = max(y0 + 2, min(y + h, frame_h)) + crop = frame[y0:y1, x0:x1] + if crop.size == 0: + return False + maps = _edge_maps(crop) + if maps is None: + return False + return _texture_ok(maps) and _palette_ok(crop) + + +def scene_shows_code(video_path, pane, start, end, samples=3): + """Sample a scene's frames inside the pane; True on a majority that read + as code. A cutaway to the camera fails and keeps the scene's other verdict. + """ + if end <= start: + return False + try: + import cv2 + except ImportError: + return False + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + return False + frames = [] + try: + n = max(1, int(samples)) + for i in range(n): + t = start + (end - start) * (i + 0.5) / n + cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000.0) + ok, frame = cap.read() + if ok: + frames.append(frame) + finally: + cap.release() + if len(frames) < 2: + return False + good = sum(1 for f in frames if frame_shows_code(f, pane)) + return good >= max(2, int(round(SCENE_CODE_FRAC * len(frames)))) + + +def looks_like_code(frames): + """Conservative fallback for deployments with no Gemini key. + + ``frames`` is a list of BGR arrays. True only when all three hold across the + samples: a static pane (centres agree), monospace row regularity, and an + editor/terminal palette (dark or mostly monochrome). This is deliberately + strict — a false positive demotes a real talking-head clip — and callers + MUST NOT invoke it over an explicit operator layout. + """ + if not frames or len(frames) < 2: + return False + planes = [] + row_projs = [] + sat_stds = [] + dark_fracs = [] + for frame in frames: + maps = _edge_maps(frame) + if maps is None: + continue + box = pane_from_projections( + maps["row_proj"], maps["col_proj"], maps["w"], maps["h"]) + if box is None: + continue + if edge_density(maps["closed"], box) < EDGE_DENSITY_FLOOR: + continue + x, y, w, h = box + crop = frame[y:y + h, x:x + w] + if crop.size == 0: + continue + hsv = _hsv(crop) + planes.append((x, y, w, h, maps["w"], maps["h"])) + row_projs.append(maps["row_proj"]) + sat_stds.append(float(hsv[:, :, 1].std())) + dark_fracs.append(float((hsv[:, :, 2] < 102).mean())) + + if len(planes) < max(2, int(round(0.6 * len(frames)))): + return False + + centres_x = np.array([(p[0] + p[2] / 2.0) / p[4] for p in planes]) + centres_y = np.array([(p[1] + p[3] / 2.0) / p[5] for p in planes]) + if centres_x.std() > 0.05 or centres_y.std() > 0.05: + return False + + median_proj = np.median(np.array(row_projs, dtype=float), axis=0) + if not _regular_rows(median_proj): + return False + + sat_std = float(np.median(sat_stds)) + dark = float(np.median(dark_fracs)) + return bool(dark >= 0.35 or sat_std <= 45.0) + + +def _hsv(crop): + import cv2 + return cv2.cvtColor(crop, cv2.COLOR_BGR2HSV) diff --git a/clipwright/layouts/layout_picker.py b/clipwright/layouts/layout_picker.py index a34e150..7deea07 100644 --- a/clipwright/layouts/layout_picker.py +++ b/clipwright/layouts/layout_picker.py @@ -64,6 +64,7 @@ SAMPLE_WIDTH = int(os.environ.get("LAYOUT_SAMPLE_WIDTH", "1024")) DECISION_FLAGS = { "none": [], "screencast": ["screencast_layout"], + "code": ["code_layout"], "split": ["split_layout", "active_speaker"], } @@ -83,11 +84,13 @@ def apply(decision): must not quietly undo that. """ from clipwright.layouts import active_speaker + from clipwright.layouts import code_layout from clipwright.layouts import screencast_layout from clipwright.layouts import split_layout modules = {"split_layout": split_layout, "screencast_layout": screencast_layout, + "code_layout": code_layout, "active_speaker": active_speaker} touched = [] diff --git a/clipwright/layouts/punch_in.py b/clipwright/layouts/punch_in.py index c76ba8f..b306270 100644 --- a/clipwright/layouts/punch_in.py +++ b/clipwright/layouts/punch_in.py @@ -14,11 +14,14 @@ It rides the TRACK path, widening the existing per-frame crop command from x-only to w/h/x/y, so it composes with the camera trajectory instead of fighting it. Off by default (``PUNCH_IN=1``). -Beat times come from the audio envelope. The transcript would be a better -source (punch on the hook word, not on the loudest syllable), and render() has -no transcript today — ``emphasis_times`` is a plain list of seconds, so wiring -main.py's word timings in later needs no change here. +Beat times come from the audio envelope, aligned to the clip-relative word +onsets the transcript provides (``emphasis_times(word_times=...)``). The +envelope finds the emphasis; the word onset says exactly when it started, so +each peak snaps to the nearest word instead of sitting on the loudest +syllable. A clip with no envelope beats falls back to the word onsets alone, +and without ``word_times`` the beat derivation is exactly what it always was. """ +import bisect import os import numpy as np @@ -59,6 +62,11 @@ BEAT_WINDOW = 0.2 MIN_GAP_SECONDS = 18.0 BEAT_PROMINENCE = 0.60 +# How far an envelope peak may move to land on a word onset. The envelope frame +# is coarse (BEAT_WINDOW); the word's start is exact, so the tolerance is a bit +# wider than the frame rather than equal to it. +WORD_SNAP_SECONDS = 0.5 + def _ease(t): """Smoothstep on [0, 1]. Linear ramps look mechanical at this duration.""" @@ -155,32 +163,72 @@ def sendcmd_lines(boxes, fps, target="crop@c"): return lines -def emphasis_times(video_path, duration, window=BEAT_WINDOW, - min_gap=MIN_GAP_SECONDS, prominence=BEAT_PROMINENCE): - """Seconds where the audio leaps above its own baseline. +def _snap_to_word(t, words, snap): + """``t`` moved to the closest onset in the sorted ``words``, if within + ``snap``. Without a word in range the envelope beat is left where it is.""" + i = bisect.bisect_left(words, t) + best, best_d = t, snap + for j in (i - 1, i): + if 0 <= j < len(words): + d = abs(words[j] - t) + if d <= best_d: + best, best_d = words[j], d + return best - A stand-in for the hook words until the transcript is wired through. Returns - [] for silent or unreadable audio, which simply means no punches. + +def merge_beats(audio_beats, word_times, min_gap=MIN_GAP_SECONDS, + snap=WORD_SNAP_SECONDS): + """Punch beats: envelope emphasis, snapped onto the words that carry it. + + The envelope finds where the energy jumped; a word onset is the precise + instant to push. Each envelope beat is snapped to the nearest word onset + within ``snap`` seconds, which is what turns "the loudest syllable" into + "the word that was loud". With no envelope beats at all — silent or flat + audio — the word onsets themselves become the beats. The result is thinned + to ``min_gap`` so two pushes never overlap. Pure: no audio, no I/O, which + is what makes the beat timing testable without a clip. + """ + words = sorted(word_times or []) + if audio_beats: + candidates = [_snap_to_word(b, words, snap) if words else b + for b in audio_beats] + else: + candidates = list(words) + + times = [] + last = -1e9 + for t in sorted(candidates): + if t - last >= min_gap: + times.append(round(t, 3)) + last = t + return times + + +def emphasis_times(video_path, duration, window=BEAT_WINDOW, + min_gap=MIN_GAP_SECONDS, prominence=BEAT_PROMINENCE, + word_times=None): + """Seconds where the clip should punch in. + + Audio envelope peaks, merged with ``word_times`` — optional clip-relative + word onsets in seconds (clip start = 0), as produced from the transcript. + Returns [] for silent, word-less input, which simply means no punches. """ from clipwright.layouts import active_speaker envelope = active_speaker.audio_envelope(video_path, 0.0, duration, window_s=window) - if not envelope: - return [] + audio_beats = [] + if envelope: + values = np.asarray(envelope, dtype=float) + baseline = float(np.median(values)) + peak = float(values.max()) + if peak - baseline > 1e-6: + threshold = baseline + (peak - baseline) * prominence + last = -1e9 + for i, v in enumerate(values): + t = i * window + if v >= threshold and t - last >= min_gap: + audio_beats.append(t) + last = t - values = np.asarray(envelope, dtype=float) - baseline = float(np.median(values)) - peak = float(values.max()) - if peak - baseline <= 1e-6: - return [] - - threshold = baseline + (peak - baseline) * prominence - times = [] - last = -1e9 - for i, v in enumerate(values): - t = i * window - if v >= threshold and t - last >= min_gap: - times.append(round(t, 3)) - last = t - return times + return merge_beats(audio_beats, word_times, min_gap=min_gap) diff --git a/clipwright/layouts/reframe_v2.py b/clipwright/layouts/reframe_v2.py index ba53c1c..b16d3b8 100644 --- a/clipwright/layouts/reframe_v2.py +++ b/clipwright/layouts/reframe_v2.py @@ -23,6 +23,7 @@ import tempfile from clipwright.layouts import active_speaker from clipwright.layouts import camera_inset +from clipwright.layouts import code_layout from clipwright.layouts import punch_in from clipwright.layouts import screencast_layout from clipwright.layouts import layout_ranges @@ -341,12 +342,15 @@ def _run(cmd): def render(input_video, final_output_video, aspect_ratio, content_ranges=None, - force_strategy=None, crop_overrides=None): + force_strategy=None, crop_overrides=None, word_times=None): """Full v2 reframe of one clip. Raises on failure (caller falls back). ``content_ranges`` comes from screencast_layout.detect_content_ranges() on - the SOURCE video, already translated into this clip's timeline. None or [] - means the layout never triggers, which is the default. + the SOURCE video, already translated into this clip's timeline. When it is + None, the render computes it itself on ``input_video`` if the screencast + module is on (see below); this used to be a dead wire no production caller + filled, so the picker's "screencast" option did nothing. Pass [] to force + the upgrade off, or a list to supply pre-computed ranges. ``force_strategy`` ('WIDE' / 'TRACK' / any layout the render loop knows) applies that layout to EVERY scene, skipping the classifier and the layout @@ -357,8 +361,13 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, listed keep the automatic camera, so correcting one bad shot never disturbs the ones the tracker got right. Applied AFTER force_strategy: a per-scene hand position always beats the whole-clip choice for the scenes it names. + + ``word_times`` are clip-relative word onsets in seconds (clip start = 0) + from the transcript, optional. They steer the punch-in beats toward spoken + emphasis; None leaves the audio envelope as the only beat source. """ from clipwright.pipeline import main as m + auto_content_ranges = content_ranges is None content_ranges = content_ranges or [] print(" 🚀 Reframe engine v2 (ffmpeg-native render)") @@ -434,6 +443,57 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, if alternates: print(f" 🎬 Speaker-cut layout on {len(alternates)} scene(s)") + # The SCREENCAST/WIDE/INSET upgrades gate on content_ranges, which no + # production caller ever passed: screencast_layout.detect_content_ranges + # was called by tests only, so the picker's "screencast" option silently did + # nothing (dead wire found in review). Compute them here, once per render, + # when the module is on and nothing overrides the layout. CODE does NOT use + # this external-ranges path — it self-detects below. + if (auto_content_ranges and screencast_layout.ENABLED + and not force_strategy and not passthrough): + duration = scene_boundaries[-1][1] / fps if scene_boundaries else 0.0 + try: + content_ranges = screencast_layout.detect_content_ranges( + input_video, duration) + except Exception as e: + print(f" ⚠️ On-screen content check failed ({e}).") + content_ranges = [] + + # CODE is geometric and self-contained, like split_layout: the pane box is + # found once for the whole video (screen recordings are usually one long + # scene) and then each scene is verified by sampling frames inside that box. + # A scene that cuts to the facecam fails the text check and keeps TRACK. + # Inserted before SCREENCAST so a code editor with a webcam wins, and the + # screencast loop below skips scenes already claimed here. + codes = {} + code_pane = None + if code_layout.ENABLED and not passthrough and not force_strategy: + try: + code_pane = code_layout.detect_code_pane(input_video) + except Exception as e: + print(f" ⚠️ Code-pane check failed ({e}) — using other layouts.") + code_pane = None + if code_pane: + max_w = max(2, int(out_w / code_layout.MIN_SCALE)) + pane_box = code_layout.clamp_pane_width(code_pane, max_w) + scale = out_w / float(pane_box[2]) + print(f" 💻 Code pane {code_pane['w']}x{code_pane['h']} " + f"@ {code_pane['x']},{code_pane['y']} " + f"mode={code_pane['mode']} conf={code_pane['confidence']:.2f}" + f" -> crop {pane_box[2]}px (scale {scale:.2f})") + code_pane = dict(code_pane, x=pane_box[0], y=pane_box[1], + w=pane_box[2], h=pane_box[3]) + for scene_idx, (start_f, end_f) in enumerate(scene_boundaries): + if strategies[scene_idx] not in ("TRACK", "GENERAL"): + continue + if code_layout.scene_shows_code( + input_video, code_pane, start_f / fps, end_f / fps): + strategies[scene_idx] = "CODE" + codes[start_f] = code_pane + splits.pop(start_f, None) + if codes: + print(f" 💻 CODE layout on {len(codes)} scene(s)") + # SCREENCAST wins over SPLIT on the rare scene that qualifies for both: two # faces beside a chart still means the chart is what the shot is about, and # stacking the two speakers would crop it away entirely. @@ -457,6 +517,9 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, if content_ranges: for scene_idx, (plan, centre) in screencast_layout.detect_screencast_scenes( input_video, scenes, strategies, content_ranges).items(): + # CODE was detected geometrically and wins over the screen layouts. + if strategies[scene_idx] == 'CODE': + continue # An inset beats both screen plans: it is the only one that can show # the screen whole AND the person at a readable size. if inset: @@ -492,7 +555,8 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, # Beats are found once per clip; each scene takes the ones inside it. beats = [] if punch_in.ENABLED: - beats = punch_in.emphasis_times(input_video, len(xs) / fps) + beats = punch_in.emphasis_times(input_video, len(xs) / fps, + word_times=word_times) if beats: print(f" 🔍 Punch-in on {len(beats)} beat(s)") @@ -544,6 +608,22 @@ def render(input_video, final_output_video, aspect_ratio, content_ranges=None, left, right = splits[start_f] graph = split_layout.split_filtergraph( orig_w, orig_h, out_w, out_h, left, right) + elif strategy == 'CODE' and start_f in codes: + pane = codes[start_f] + follow = None + if code_layout.FOLLOW_ENABLED: + try: + series = code_layout.active_line_series( + input_video, pane, ss, ss + dur) + if series: + follow = [(t - ss, y) for t, y in series] + except Exception: + follow = None + graph = code_layout.code_filtergraph( + pane, out_w, out_h, follow=follow) + if graph is None: + graph = general_filtergraph(out_w, out_h, + orig_w=orig_w, orig_h=orig_h) elif strategy == 'GENERAL': graph = general_filtergraph(out_w, out_h, orig_w=orig_w, orig_h=orig_h) diff --git a/clipwright/media/thumbnail.py b/clipwright/media/thumbnail.py index 45fbf14..a3754a7 100644 --- a/clipwright/media/thumbnail.py +++ b/clipwright/media/thumbnail.py @@ -10,6 +10,8 @@ from google.genai import types from google.genai import errors as genai_errors from PIL import Image, ImageDraw, ImageFont, ImageFilter from clipwright.core.paths import FONTS_DIR +from clipwright.media import title_validation +from clipwright.pipeline import profile_prompts # Text/analysis model (titles, concepts, description). Deliberately NOT tied to # GEMINI_MODEL: the pipeline runs flash-lite for a closed-choice layout pick, @@ -34,6 +36,14 @@ THUMB_MAX_BYTES = 2 * 1024 * 1024 # YouTube's upload limit THUMB_FONT = str(FONTS_DIR / "Anton-Regular.ttf") TEXT_POSITIONS = ("left", "right", "top", "bottom") +# Mobile viewers (the majority of the audience) watch with YouTube's +# timestamp/badge overlays in the bottom-right; keep the headline clear of that +# corner and off the right edge. +THUMB_SAFE_BOTTOM = 0.20 # bottom fraction reserved for YouTube's UI +THUMB_SAFE_RIGHT = 0.05 # margin off the right edge +THUMB_SAFE_LEFT = 0.04 # margin off the left edge +THUMB_SAFE_TOP = 0.04 # margin off the top edge + def _parse_json(text): """Gemini JSON, tolerant of code fences and prose around the object.""" @@ -62,11 +72,14 @@ def _frame_parts(video_path, n=TITLE_FRAMES, width=TITLE_FRAME_WIDTH): # Titles # --------------------------------------------------------------------------- -def analyze_video_for_titles(api_key, video_path, transcript=None): +def analyze_video_for_titles(api_key, video_path, transcript=None, profile=None): """ Suggests YouTube titles from the transcript plus a handful of frames. Two calls: a wide brainstorm, then a critic that scores and picks a diverse top 10 and pairs each title with a 1-4 word thumbnail hook. + + ``profile`` (optional channel Profile, PLAN #1) adds the channel's title and + hook rules to both calls; ``None`` leaves the prompts unchanged. Returns: { "titles", "thumbnail_texts", "transcript_summary", "language", "segments", "video_duration", "recommended" } """ @@ -84,6 +97,11 @@ def analyze_video_for_titles(api_key, video_path, transcript=None): video_duration = segments[-1]["end"] if segments else 0 # Enough transcript for a title; a 3-hour podcast does not need all of it. transcript_text = transcript.get("text", "")[:60000] + # Empty for profile=None, so the f-strings below render exactly as before. + channel_rules = profile_prompts.clip_rules_block(profile) + if channel_rules: + print(f"📦 [Thumbnail] Applying channel profile " + f"{getattr(profile, 'slug', '')} to title prompts.") brainstorm_prompt = f"""You are a YouTube packaging expert (titles + thumbnails) for a channel that wants maximum CTR without lying. @@ -109,7 +127,7 @@ TITLE RULES: - Put the main keyword / subject in the first 3 words. - Be specific to THIS video: names, numbers, tools, places from the transcript. Nothing generic. - No ALL CAPS words, at most one exclamation mark, no emojis. - +{channel_rules} OUTPUT JSON: {{ "transcript_summary": "...", @@ -154,7 +172,7 @@ Then return the 10 best, ordered best first, with NO two titles using the same a For each of the 10, write the THUMBNAIL TEXT: 1-4 words, ALL CAPS, in {language}, that COMPLEMENTS the title instead of repeating it (the title says what, the thumbnail says the emotion, the number or the twist). Examples of the relationship: title "How I got 10k subscribers in 30 days" -> thumbnail "0 TO 10K"; title "Por qué dejé mi trabajo en Google" -> thumbnail "ME FUI". Pick the top 2 and explain in one sentence each why they will win the click. - +{channel_rules} OUTPUT JSON: {{ "titles": ["...", ... 10 items], @@ -166,21 +184,50 @@ OUTPUT JSON: }}""" print("🧐 [Thumbnail] Scoring titles...") - response = client.models.generate_content( - model=TEXT_MODEL, - contents=[critic_prompt], - config=types.GenerateContentConfig(response_mime_type="application/json"), - ) - try: - picked = _parse_json(response.text) - titles = [t for t in picked.get("titles", []) if isinstance(t, str) and t.strip()] - if not titles: - raise ValueError("no titles") - except (json.JSONDecodeError, AttributeError, ValueError): - print(f"⚠️ [Thumbnail] Critic failed, falling back to the brainstorm: {getattr(response, 'text', '')[:300]}") - titles = candidates[:10] - picked = {"thumbnail_texts": [], "recommended": []} + def _critic(violations=None): + """One critic call. ``violations`` appends the re-ask critique.""" + prompt = critic_prompt + if violations: + prompt = critic_prompt + "\n\n" + title_validation.critique_block(violations) + response = client.models.generate_content( + model=TEXT_MODEL, + contents=[prompt], + config=types.GenerateContentConfig(response_mime_type="application/json"), + ) + try: + picked_local = _parse_json(response.text) + titles_local = [t for t in picked_local.get("titles", []) + if isinstance(t, str) and t.strip()] + if not titles_local: + raise ValueError("no titles") + except (json.JSONDecodeError, AttributeError, ValueError): + print(f"⚠️ [Thumbnail] Critic failed: {getattr(response, 'text', '')[:300]}") + return None + texts_local = [str(t) for t in picked_local.get("thumbnail_texts", [])][:len(titles_local)] + texts_local += [""] * (len(titles_local) - len(texts_local)) + return { + "titles": titles_local, + "thumbnail_texts": texts_local, + "recommended": [r for r in picked_local.get("recommended", []) + if isinstance(r, dict) and isinstance(r.get("index"), int) + and 0 <= r["index"] < len(titles_local)], + } + + def _validate(candidate): + if not candidate: + return [] + return title_validation.validate_titles(candidate["titles"], profile) + + # Deterministic QA (PLAN #3): one re-ask if the critic's titles break the + # channel rules, then keep the best attempt. Never blocks the response. + picked = title_validation.run_with_validation( + _critic, _validate, lambda violations: _critic(violations)) + if picked is None: + print("⚠️ [Thumbnail] Critic failed, falling back to the brainstorm candidates.") + picked = {"titles": candidates[:10], "thumbnail_texts": [], "recommended": []} + + titles = picked["titles"] thumbnail_texts = [str(t) for t in picked.get("thumbnail_texts", [])][:len(titles)] thumbnail_texts += [""] * (len(titles) - len(thumbnail_texts)) return { @@ -190,9 +237,7 @@ OUTPUT JSON: "language": language, "segments": segments, "video_duration": video_duration, - "recommended": [r for r in picked.get("recommended", []) - if isinstance(r, dict) and isinstance(r.get("index"), int) - and 0 <= r["index"] < len(titles)], + "recommended": picked.get("recommended", []), } @@ -370,11 +415,15 @@ def _crop_face_reference(frame_path, face_box, out_path): # --------------------------------------------------------------------------- def plan_thumbnail_concepts(client, title, count, video_context="", extra_prompt="", - thumbnail_text_hint="", has_person=False, language="en"): + thumbnail_text_hint="", has_person=False, language="en", + profile=None): """ One text call that designs `count` DIFFERENT thumbnails before any pixel is drawn. Asking the image model to invent the concept and render it in one go gives N variations of one idea; splitting it gives N ideas. + + ``profile`` (optional channel Profile, PLAN #1) adds the channel's palette, + role order and presenter expectation; ``None`` leaves the prompt unchanged. """ person_line = ("A real photo of the presenter is provided and MUST be the focal point, " "with a clear, natural expression that reads at small size (no caricature)." @@ -385,6 +434,8 @@ def plan_thumbnail_concepts(client, title, count, video_context="", extra_prompt hint_line = (f'\nSUGGESTED THUMBNAIL TEXT (use it for the first concept unless it is poor): "{thumbnail_text_hint}"' if thumbnail_text_hint else "") extra_line = f"\nMANDATORY USER INSTRUCTIONS (override everything else):\n{extra_prompt}\n" if extra_prompt else "" + # Empty for profile=None, so the f-string below renders exactly as before. + channel_rules = profile_prompts.thumbnail_block(profile) prompt = f"""You are a YouTube thumbnail art director. Design {count} DIFFERENT thumbnail concepts for this video. VIDEO TITLE: "{title}" @@ -394,17 +445,18 @@ VIDEO CONTEXT: {video_context or "(none)"} The thumbnail must show WHAT the video is about, not only how the presenter feels: name the concrete subject (the product, the tool, the result, the numbers) and build the picture around it. A face alone with two words is the lazy default; use it at most once, and only combined with a strong prop or scene. Each concept must use a different device, e.g.: the presenter + a prop that IS the topic (a phone showing vertical clips, a laptop with the app, a counter/badge with the number); before/after or "long video -> short clips" split; product/UI hero shot with the presenter small; a giant number or stat as the hero with the subject behind; "X vs Y" comparison; a red circle/arrow on a detail; a dramatic reveal with depth (foreground object, blurred background). Layered, cinematic, premium: real props, depth of field, rim light, particles, glow on the key object. Never flat, never a plain wall behind the person. No two concepts may share the same text or the same layout. - +{channel_rules} Per concept give: - "text": 1-4 words, ALL CAPS, in {language}. Complements the title (the title says what, the text says the emotion, the number or the twist). Never repeat the title. No emoji. - "text_position": one of "left", "right", "top", "bottom" (where the text block sits; the subject goes on the opposite side). - "text_color": "white" or "yellow" (yellow for money/energy, white otherwise). +- "role": exactly one of "emotion", "technical", "curiosity" — the job this concept does for the click. Cover ALL THREE roles across the set (at least one of each): "emotion" is a human face or feeling, "technical" is the product, tool, code, diagram or concrete result, "curiosity" is a question, a reveal or a hidden detail. - "scene": a precise image-generation prompt in English, 2-4 sentences: subject, expression/pose, background, lighting, colours, camera. Say that the text_position side is clean negative space (simple, dark or plain) so a headline can sit there. It must NOT ask for any text, letters, captions or logos in the image. - The image model REFUSES prompts that name or depict real people, companies or brands. Never write a real name (person, company, product, logo) in "scene". Refer to the presenter only as "the person in the provided photo" when a photo is provided, otherwise as a generic, unnamed person or use objects and symbols. - "why": one short sentence on why this earns the click. OUTPUT JSON: -{{"concepts": [{{"text": "...", "text_position": "left", "text_color": "yellow", "scene": "...", "why": "..."}}, ...]}}""" +{{"concepts": [{{"text": "...", "text_position": "left", "text_color": "yellow", "role": "emotion", "scene": "...", "why": "..."}}, ...]}}""" response = client.models.generate_content( model=TEXT_MODEL, @@ -416,32 +468,96 @@ OUTPUT JSON: except (json.JSONDecodeError, AttributeError): print(f"⚠️ [Thumbnail] Concept JSON unreadable, using a generic concept: {getattr(response, 'text', '')[:200]}") concepts = [] - return normalise_concepts(concepts, count, title, thumbnail_text_hint) + role_order = list(profile.thumbnail.role_order) if profile else None + return normalise_concepts(concepts, count, title, thumbnail_text_hint, + role_order=role_order) -def normalise_concepts(concepts, count, title, thumbnail_text_hint=""): - """Clamp model output to what the renderer accepts and pad to `count`.""" +# #4: every concept declares the job it does for the click, and the set must +# cover emotion + technical. Kept here (not in the prompt alone) because a +# prompt is not a contract. +CONCEPT_ROLES = ("emotion", "technical", "curiosity") + +_ROLE_SCENES = { + "emotion": ( + "A dramatic, high-contrast YouTube thumbnail centred on a person's face and " + "expression (surprise, focus or relief), warm rim light, blurred background, " + "the {pos} side clean dark negative space."), + "technical": ( + "A clean product/UI hero shot for a video titled '{title}': the tool, code, " + "diagram or result sharp and large, cool cinematic light, the {pos} side " + "clean dark negative space."), + "curiosity": ( + "A cinematic reveal for a video titled '{title}': a key detail partly hidden " + "or circled, depth of field, dramatic light, the {pos} side clean dark " + "negative space."), +} + + +def _role_scene(role, title, position): + template = _ROLE_SCENES.get(role, _ROLE_SCENES["curiosity"]) + return template.format(title=title, pos=position) + + +def _fallback_concept(title, hint, role, position="left"): + return { + "text": (hint or "").upper()[:40], + "text_position": position, + "text_color": "white", + "role": role, + "scene": _role_scene(role, title, position), + "why": f"fallback ({role})", + } + + +def normalise_concepts(concepts, count, title, thumbnail_text_hint="", role_order=None): + """Clamp model output to what the renderer accepts and pad to `count`. + + Also enforces the #4 role mix: every concept carries a role and the set is + guaranteed at least one "emotion" and one "technical" concept. A missing + role is filled by converting the last available concept to a role-appropriate + scene, so no concept is dropped. + """ cleaned = [] for c in concepts: if not isinstance(c, dict) or not c.get("scene"): continue + role = c.get("role") if c.get("role") in CONCEPT_ROLES else None cleaned.append({ "text": str(c.get("text") or thumbnail_text_hint or "").strip().upper()[:40], "text_position": c.get("text_position") if c.get("text_position") in TEXT_POSITIONS else "left", "text_color": "yellow" if c.get("text_color") == "yellow" else "white", + "role": role, "scene": str(c["scene"]), "why": str(c.get("why", "")), }) + + order = [r for r in (role_order or []) if r in CONCEPT_ROLES] or list(CONCEPT_ROLES) while len(cleaned) < count: - cleaned.append({ - "text": thumbnail_text_hint.upper()[:40], - "text_position": "left", - "text_color": "white", - "scene": (f"A bold, high-contrast YouTube thumbnail scene for a video titled '{title}'. " - "Dramatic lighting, vibrant colours, the left third is clean dark negative space."), - "why": "fallback", - }) - return cleaned[:count] + role = order[len(cleaned) % len(order)] + cleaned.append(_fallback_concept(title, thumbnail_text_hint, role)) + cleaned = cleaned[:count] + + if count < 2: + return cleaned + + present = {c["role"] for c in cleaned} + used: set[int] = set() + for role in ("emotion", "technical"): + if role in present: + continue + target = next((c for c in reversed(cleaned) + if c["role"] is None and id(c) not in used), None) + if target is None: + target = next((c for c in reversed(cleaned) if id(c) not in used), None) + if target is None: + break + used.add(id(target)) + target["role"] = role + target["scene"] = _role_scene(role, title, target["text_position"]) + target["why"] = target["why"] or f"{role} concept" + present.add(role) + return cleaned def _wrap_lines(draw, text, font, max_width): @@ -502,8 +618,46 @@ def burn_thumbnail_text(img, text, position="left", color="white"): else: x0, y0 = int(W * 0.04), H - total_h - int(H * 0.06) - top_pad + # Bottom-right safe area (#4): the headline must not sit under YouTube's + # timestamp/badge corner nor run off the right edge. Whatever the requested + # position, the rendered block is clamped inside the safe box. + bottom_limit = int(H * (1.0 - THUMB_SAFE_BOTTOM)) + right_limit = int(W * (1.0 - THUMB_SAFE_RIGHT)) + left_limit = int(W * THUMB_SAFE_LEFT) + top_limit = int(H * THUMB_SAFE_TOP) + + center_x = W // 2 + ink_w = widest + stroke + ink_h = total_h + stroke + if horizontal: + block_left, block_right = x0, x0 + ink_w + else: + block_left, block_right = center_x - ink_w // 2, center_x + ink_w // 2 + if block_right > right_limit: + shift = block_right - right_limit + if horizontal: + x0 -= shift + else: + center_x -= shift + if block_left < left_limit: + shift = left_limit - block_left + if horizontal: + x0 += shift + else: + center_x += shift + + visual_top = y0 + top_pad + if visual_top < top_limit: + y0 += top_limit - visual_top + visual_top = top_limit + if visual_top + ink_h > bottom_limit: + y0 = bottom_limit - ink_h - top_pad + y0 = max(y0, -top_pad) # keep the ink on the canvas + def line_x(line): - return x0 if horizontal else (W - draw.textlength(line, font=font)) // 2 + if horizontal: + return x0 + return center_x - int(draw.textlength(line, font=font)) // 2 shadow = Image.new("RGBA", img.size, (0, 0, 0, 0)) sdraw = ImageDraw.Draw(shadow) @@ -663,11 +817,13 @@ Style: high contrast, saturated colours, crisp subject separation, cinematic lig def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_image_path=None, extra_prompt="", count=3, video_context="", burn_text=True, - thumbnail_text_hint="", language="en", frame_reference=None): + thumbnail_text_hint="", language="en", frame_reference=None, + profile=None): """ Generates `count` thumbnails, each from its own concept, in parallel. frame_reference: {"path", "face"} from extract_face_frames, used as the person reference when the user picked a frame instead of uploading a photo. + profile: optional channel Profile (PLAN #1), forwarded to the concept call. Returns [{"url", "text", "why"}] (only the ones that rendered). """ client = genai.Client(api_key=api_key) @@ -688,7 +844,8 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag concepts = plan_thumbnail_concepts( client, title, count, video_context=video_context, extra_prompt=extra_prompt, - thumbnail_text_hint=thumbnail_text_hint, has_person=bool(reference_images), language=language) + thumbnail_text_hint=thumbnail_text_hint, has_person=bool(reference_images), + language=language, profile=profile) for i, c in enumerate(concepts): print(f"🎨 [Thumbnail] Concept {i + 1}: \"{c['text']}\" ({c['text_position']}) - {c['why']}") @@ -720,7 +877,8 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag fallback = True print(f"✅ [Thumbnail] Saved: {out_path}") return {"url": f"/thumbnails/{session_id}/{os.path.basename(out_path)}", - "text": concept["text"], "why": concept["why"], "fallback": fallback} + "text": concept["text"], "why": concept["why"], + "role": concept.get("role"), "fallback": fallback} except Exception as e: print(f"❌ [Thumbnail] Generation {i + 1} failed: {e}") return {"error": str(e)} @@ -739,9 +897,12 @@ def generate_thumbnail(api_key, title, session_id, face_image_path=None, bg_imag # Description # --------------------------------------------------------------------------- -def generate_youtube_description(api_key, title, transcript_segments, language, video_duration): +def generate_youtube_description(api_key, title, transcript_segments, language, video_duration, + profile=None): """ Uses Gemini to generate a YouTube description with chapter markers from transcript segments. + ``profile`` (optional channel Profile, PLAN #1) adds the channel's description + structure, links and tone; ``None`` leaves the prompt unchanged. Returns: { "description": "full description text with chapters" } """ client = genai.Client(api_key=api_key) @@ -762,6 +923,9 @@ def generate_youtube_description(api_key, title, transcript_segments, language, dur_secs = int(video_duration % 60) duration_str = f"{dur_mins}:{dur_secs:02d}" + # Empty for profile=None, so the f-string below renders exactly as before. + channel_rules = profile_prompts.description_block(profile) + prompt = f"""You are a YouTube SEO expert. Generate a complete YouTube video description for the following video. VIDEO TITLE: "{title}" @@ -783,7 +947,7 @@ REQUIREMENTS: - Place chapters in their own section with a blank line before and after 5. Add 5-10 relevant hashtags at the end 6. Keep the total description under 5000 characters - +{channel_rules} OUTPUT: Return ONLY the description text (no JSON wrapper, no markdown code blocks). The description should be ready to paste directly into YouTube.""" print("🤖 [Thumbnail] Generating YouTube description with chapters...") diff --git a/clipwright/media/title_validation.py b/clipwright/media/title_validation.py new file mode 100644 index 0000000..51b4b9d --- /dev/null +++ b/clipwright/media/title_validation.py @@ -0,0 +1,170 @@ +"""Deterministic YouTube title QA (PLAN #3 + #4, merged). + +No LLM call lives here: the rules are the active channel profile's +``title_rules`` plus a few universal structural checks, so validation is cheap +enough to run on every generated title and cannot itself hallucinate. + +Two entry points: +* :func:`validate_title` / :func:`validate_titles` return the list of human- + readable violations for one title, or for a set (structural rules). +* :func:`run_with_validation` wraps generation: try, and on violations re-ask + exactly once with the critique; if the retry does not improve, keep the first + attempt. It NEVER raises on a validation failure and never blocks the job. +""" + +from __future__ import annotations + +import re +from collections import Counter + +from clipwright.pipeline.profiles import Profile + +# Task-descriptive openers that describe what the video *does* rather than what +# the viewer gets. The profile's ``banned_openers`` add the channel's own. +_TASK_OPENERS = ( + "in this video", "in today's video", "this video", "explaining", "discussing", + "talking about", "a look at", "let's", "watch me", "i'm going to", + "im going to", "here's how i", "step by step", +) +_TASK_OPENER_RE = re.compile( + r"^(?:" + "|".join(re.escape(o) for o in _TASK_OPENERS) + r")\b", re.I) + +# Words that carry no topic, so a title starting with one has not front-loaded +# its keyword. This is the deterministic proxy for ``keyword_position="start"`` +# (the profile carries no keyword to locate precisely). +_STOPWORDS = frozenset({ + "the", "a", "an", "this", "that", "these", "those", "my", "your", "our", + "their", "his", "her", "its", "it", "i", "we", "you", "they", "he", "she", + "is", "are", "was", "were", "be", "been", "being", "as", "if", "when", + "while", "so", "just", "in", "on", "at", "of", "for", "to", "with", "from", + "by", "and", "but", "or", +}) + +# Broad cue sets for required_signal. Deliberately generous: a false negative +# would force a retry, and a false positive only lets a weaker title through. +_CONSEQUENCE_RE = re.compile( + r"\b(why|because|so that|cost|costs|costing|ruin|ruined|ruins|broke|broken|" + r"breaks|lost|lose|loses|win|won|wins|crashed|crash|crashes|fail|failed|" + r"fails|failure|change|changed|changes|makes|made|turns|turned|becomes|became|" + r"stops|stopped|kills|killed|destroy|destroyed|saved|saves|before|after|" + r"mistake|mistakes|warning|warns|secretly|almost|never again|no longer|" + r"instead)\b", re.I) +_CURIOSITY_RE = re.compile( + r"\?|\b(why|how|what|secret|truth|real reason|reason|hidden|nobody|everyone|" + r"no one|shouldn'?t|should not|impossible|actually|forgot|forgotten|never|" + r"finally|revealed|reveal|mystery|unknown|here'?s|looks like|seems)\b", re.I) + + +def _first_word(title: str) -> str: + match = re.match(r"\s*([A-Za-zÀ-ÿ0-9']+)", title or "") + return match.group(1).lower() if match else "" + + +def validate_title(title: str, profile: Profile | None) -> list[str]: + """Every reason this one title breaks the profile's title rules. + + Structural checks (task-descriptive openers) run with or without a profile; + the profile-specific checks are skipped when ``profile`` is None. + """ + title = (title or "").strip() + if not title: + return ["title is empty"] + + problems: list[str] = [] + rules = getattr(profile, "title_rules", None) + if rules is not None: + if len(title) > rules.max_chars: + problems.append(f"{len(title)} chars exceeds the {rules.max_chars}-char maximum") + elif len(title) > rules.mobile_chars: + problems.append( + f"{len(title)} chars exceeds the {rules.mobile_chars}-char mobile limit") + lowered = title.lower() + for pattern in rules.banned_patterns: + if pattern.lower() in lowered: + problems.append(f'uses the banned phrase "{pattern}"') + for opener in rules.banned_openers: + if lowered.startswith(opener.lower()): + problems.append(f'opens with the banned opener "{opener}"') + break + first = _first_word(title) + if rules.keyword_position == "start" and first in _STOPWORDS: + problems.append(f'starts with the filler word "{first}" instead of the keyword') + if rules.number_policy == "avoid" and re.search(r"\d", title): + problems.append("uses a number where the channel avoids them") + elif rules.number_policy == "require" and not re.search(r"\d", title): + problems.append("has no number, which this channel requires") + signal = rules.required_signal + consequence = bool(_CONSEQUENCE_RE.search(title)) + curiosity = bool(_CURIOSITY_RE.search(title)) + if signal == "consequence" and not consequence: + problems.append("carries no consequence or stake") + elif signal == "curiosity" and not curiosity: + problems.append("opens no curiosity gap the video pays off") + elif signal == "either" and not (consequence or curiosity): + problems.append("carries no consequence or curiosity signal") + + if _TASK_OPENER_RE.match(title): + problems.append("opens with a task-descriptive phrase") + return problems + + +def validate_titles(titles, profile: Profile | None) -> list[str]: + """Per-title violations plus the structural rules that span a title set.""" + clean = [t for t in (titles or []) if isinstance(t, str) and t.strip()] + problems: list[str] = [] + for i, title in enumerate(clean): + for problem in validate_title(title, profile): + problems.append(f"title {i + 1}: {problem}") + + if not clean: + problems.append("no titles") + + firsts = Counter(_first_word(t) for t in clean) + for word, count in firsts.items(): + if word and count > 3: + problems.append(f'{count} titles start with the same word "{word}" (max 3)') + colons = sum(1 for t in clean if ":" in t) + if colons > 2: + problems.append(f"{colons} titles use a colon pattern (max 2)") + return problems + + +def critique_block(violations) -> str: + """An instruction block that hands the model the exact violations to fix.""" + lines = ["VALIDATION FAILED — the previous titles broke these rules:"] + lines += [f"- {v}" for v in violations] + lines.append("Rewrite the titles so every rule passes; keep every other instruction.") + return "\n".join(lines) + + +def run_with_validation(generate, validate, retry_once): + """Try ``generate``; on violations re-ask exactly once and keep the best. + + ``generate()`` -> candidate + ``validate(candidate)`` -> list of violations + ``retry_once(violations)`` -> a new candidate, or None if it could not run + + Returns the candidate with the fewest violations (the first one on a tie or + a failed retry). Never raises because of a validation failure. + """ + candidate = generate() + violations = list(validate(candidate) or []) + if not violations: + return candidate + + try: + retry = retry_once(violations) + except Exception as e: # a broken retry must not lose the first attempt + print(f"⚠️ [titles] validation retry failed ({e}); keeping the first attempt.") + return candidate + if retry is None: + return candidate + + retry_violations = list(validate(retry) or []) + if len(retry_violations) < len(violations): + print(f"✅ [titles] retry reduced violations " + f"{len(violations)} -> {len(retry_violations)}.") + return retry + print(f"⚠️ [titles] retry did not improve " + f"({len(violations)} -> {len(retry_violations)}); keeping the first attempt.") + return candidate diff --git a/clipwright/pipeline/bridge.py b/clipwright/pipeline/bridge.py new file mode 100644 index 0000000..ceaf713 --- /dev/null +++ b/clipwright/pipeline/bridge.py @@ -0,0 +1,207 @@ +"""Shorts -> long-form bridge copy (PLAN #6). + +Pure, network-free helpers that turn the active channel profile (+ its +``published_video_history``) into the copy a Short needs to funnel viewers to a +long-form video: + +* ``description_bridge`` -- a block appended to the Short's YouTube description; +* ``first_comment`` -- the top-level comment to post (and pin). + +Two "related video" features are Studio-UI only and are **not** exposed by any +API: the Shorts "Related video" link and comment pinning. Those therefore stay +manual, and ``checklist`` spells out the exact Studio steps including the +target long-form URL. + +The explicit target wins over the profile history. Callers pass it from the CLI +(``--longform-url``) or the API (``related_video_url``); nothing here performs +I/O. +""" + +from __future__ import annotations + +from typing import Any, Mapping, Optional + +from clipwright.pipeline import profile_prompts +from clipwright.pipeline.profiles import Profile + +# Fallback label when the target URL is provided but the profile says nothing. +DEFAULT_TARGET_LABEL = "Full video" + +# Keys a published_video_history entry may carry to identify the video. The +# first match wins; ``id``/``video_id`` build a watch URL. +_URL_KEYS = ("url", "video_url", "watch_url", "link") +_ID_KEYS = ("id", "video_id", "youtube_id") +_DATE_KEYS = ("published_at", "published", "date", "uploaded_at") + + +def _entry_url(entry: Mapping) -> Optional[str]: + """The watch URL for one ``published_video_history`` entry, or None.""" + if not isinstance(entry, Mapping): + return None + for key in _URL_KEYS: + value = entry.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + for key in _ID_KEYS: + value = entry.get(key) + if isinstance(value, str) and value.strip(): + return f"https://www.youtube.com/watch?v={value.strip()}" + return None + + +def _entry_sort_key(entry: Mapping) -> str: + for key in _DATE_KEYS: + value = entry.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +def target_video(profile: Optional[Profile], + related_video_url: Optional[str] = None) -> Optional[str]: + """The long-form target: the explicit URL, else the newest history entry. + + An explicit ``related_video_url`` always wins. Otherwise the profile's + ``published_video_history`` is searched for an entry that names a video + (``url``/``video_url``/... or an ``id``); the newest by a best-effort date + field is chosen, falling back to the last entry listed. + """ + if isinstance(related_video_url, str) and related_video_url.strip(): + return related_video_url.strip() + history = list(getattr(profile, "published_video_history", None) or []) + candidates = [(k, e) for e in history if (k := _entry_url(e))] + if not candidates: + return None + candidates.sort(key=lambda pair: _entry_sort_key(pair[1])) + return candidates[-1][0] + + +def _target_label(profile: Optional[Profile]) -> str: + """A human label for the target, derived from the profile's description.""" + template = getattr(profile, "description_template", "") if profile else "" + # Templates look like "{hook}\n\nFull video: {link}\n\n#tags" -- lift the + # words before "{link}" when they name the long-form video. + if "{link}" in template: + prefix = template.split("{link}")[0].strip().splitlines()[-1].strip() + prefix = prefix.rstrip(":").strip() + if prefix and "{hook}" not in prefix: + return prefix + return DEFAULT_TARGET_LABEL + + +def _clip_hook(clip: Optional[Mapping]) -> str: + """The clip's hook text if the pipeline produced one, else its title.""" + if not isinstance(clip, Mapping): + return "" + for key in ("viral_hook_text", "hook_text", "video_title_for_youtube_short"): + value = clip.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +def _render_description_template(template: str, target: Optional[str], + clip: Optional[Mapping]) -> str: + """Fill the profile's ``{hook}``/``{link}`` slots without str.format. + + ``str.format`` would explode on any other brace in the template (or + hashtags that are fine today); a literal replace can only touch the two + documented placeholders. + """ + rendered = template.replace("{hook}", _clip_hook(clip)) + rendered = rendered.replace("{link}", target or "") + return "\n".join(line.rstrip() for line in rendered.splitlines()).strip() + + +def description_bridge(profile: Optional[Profile], + related_video_url: Optional[str] = None, + clip: Optional[Mapping] = None) -> str: + """The description block: a target CTA plus the profile's description copy. + + The target URL appears first (and in the rendered template when the profile + has one). Without a target the channel links/description still render, so a + bridge is produced even before a long-form URL is chosen. + """ + target = target_video(profile, related_video_url) + parts: list[str] = [] + if target: + parts.append(f"▶ {_target_label(profile)}: {target}") + + template = (getattr(profile, "description_template", "") if profile else "") or "" + rendered = _render_description_template(template, target, clip) if template else "" + if rendered: + parts.append(rendered) + else: + # No template: fall back to the profile's plain description block. + block = profile_prompts.description_block(profile) if profile else "" + if block: + parts.append(block.rstrip()) + + # The profile's links belong in the bridge even when the template's {link} + # slot was empty (no target yet) or the template does not mention them. + links = [link for link in (getattr(profile, "links", None) or []) + if isinstance(link, str) and link.strip()] + if links and not any(link in "\n".join(parts) for link in links): + parts.append("More from this channel: " + " | ".join(links)) + + return "\n\n".join(p for p in parts if p).strip() + + +def first_comment(profile: Optional[Profile], + related_video_url: Optional[str] = None, + clip: Optional[Mapping] = None) -> str: + """The top-level comment text. Always carries the long-form reference. + + With no target it points at the channel's links (or the description) rather + than inventing a URL; it is never empty. + """ + target = target_video(profile, related_video_url) + hook = _clip_hook(clip) + if target: + text = f"▶ {_target_label(profile)}: {target}" + if hook: + text += f"\n\n{_target_label(profile)} covers this: {hook}" + return text + links = list(getattr(profile, "links", None) or []) + if links: + return f"Watch the long-form videos here: {links[0]}" + return "The full long-form video is linked in the description." + + +def checklist(profile: Optional[Profile], + related_video_url: Optional[str] = None) -> list[str]: + """The manual Studio steps for this Short (both are Studio-UI only). + + The Shorts "Related video" link and comment pinning have no public API, so + they are copy-paste steps, not something the server can do. + """ + target = target_video(profile, related_video_url) + target_text = target or "" + return [ + "Open YouTube Studio -> Content -> this Short -> Edit.", + f"Details -> Related video: set it to {target_text} " + "(the Shorts related-video link is Studio-UI only; no API can set it).", + "Post the generated first comment " + "(or call this clip's bridge/comment endpoint if the YouTube Data API " + "is configured).", + "Pin the first comment: hover it -> the three-dot menu -> Pin. " + "Pinning stays manual (no API).", + ] + + +def build_bridge(profile: Optional[Profile], + clip: Optional[Mapping] = None, + related_video_url: Optional[str] = None) -> dict[str, Any]: + """All bridge fields for one clip, ready to merge into clip metadata. + + ``related_video_url`` is the explicit target (CLI ``--longform-url`` / API + ``related_video_url``); when omitted the profile history is used. + """ + target = target_video(profile, related_video_url) + return { + "related_video_url": target, + "description_bridge": description_bridge(profile, target, clip), + "first_comment": first_comment(profile, target, clip), + "checklist": checklist(profile, target), + "manual_pin_required": True, + } diff --git a/clipwright/pipeline/clip_selection.py b/clipwright/pipeline/clip_selection.py index 0b75093..229d8d8 100644 --- a/clipwright/pipeline/clip_selection.py +++ b/clipwright/pipeline/clip_selection.py @@ -5,6 +5,8 @@ Standard-library only so both main.py and gemini_worker.py can import it and the logic stays unit-testable without the heavy video dependencies. """ +import re + # USD per 1M tokens (input, output incl. thinking), from ai.google.dev pricing. MODEL_PRICES = { "gemini-3.5-flash": (1.50, 9.00), @@ -348,3 +350,185 @@ def snap_clip_to_words(start, end, words, video_duration, if new_end <= new_start or new_end - new_start < min_duration: return original return (round(new_start, 3), round(new_end, 3)) + + +# --- Hook-first boundaries (#2a) ------------------------------------------- +# The first seconds decide the swipe. A model-proposed clip routinely opens on +# wind-up ("so today we're going to...") and buries the question, the number or +# the stakes 3-8s in. Word timestamps are ground truth, so the start can be +# moved onto the first strong spoken hook deterministically — no LLM, no key. +# +# These are the signal vocabularies the scan combines. A token matching ANY set +# is a hook; the EARLIEST such token inside the allowed trim window wins. They +# are deliberately conservative: a miss leaves the clip untouched, a false +# positive only advances the start a bounded amount (see the env caps). +_HOOK_INTERROGATIVES = frozenset({ + "what", "why", "how", "when", "where", "who", "whom", "whose", "which", + "is", "are", "was", "were", "do", "does", "did", "can", "could", "would", + "should", "will", "shall", +}) +_HOOK_IMPERATIVES = frozenset({ + "look", "watch", "imagine", "think", "stop", "try", "check", "see", + "listen", "remember", "forget", "consider", "notice", "suppose", "picture", + "keep", "take", "put", "go", "come", "use", "make", "let", "dont", "show", + "tell", "explain", "build", "create", "write", "read", "open", "close", + "click", "press", "type", "install", "run", "fix", "never", "always", +}) +_HOOK_NUMBERS = frozenset({ + "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", + "nine", "ten", "eleven", "twelve", "hundred", "thousand", "million", + "billion", "half", "quarter", "twice", "once", "double", "triple", + "dozen", "percent", "first", "second", "third", +}) +_HOOK_CONTRAST = frozenset({ + "but", "until", "actually", "instead", "except", "however", "though", + "although", "whereas", "yet", "still", "suddenly", "wait", "unless", + "otherwise", "despite", "nevertheless", "contrary", "opposite", "reverse", +}) +_HOOK_STAKES = frozenset({ + "never", "always", "first", "worst", "bug", "bugs", "crash", "crashes", + "crashed", "crashing", "broke", "broken", "break", "wrong", "lost", "lose", + "losing", "fail", "failed", "fails", "failure", "dies", "death", "dead", + "kill", "killed", "destroy", "destroyed", "ruin", "ruined", "disaster", + "mistake", "error", "errors", "segfault", "danger", "dangerous", "scared", + "terrified", "panic", "emergency", "critical", "fatal", "illegal", + "corrupt", "corrupted", "hacked", "stolen", "missing", "gone", "worse", +}) +# Pure hesitation / connective words that are never hooks. The scan simply +# walks past them, so they end up in the trimmed wind-up; they must not count. +_HOOK_FILLER = frozenset({ + "uh", "um", "erm", "ah", "eh", "hmm", "mmm", "so", "well", "okay", "ok", + "yeah", "yep", "right", "and", "then", "like", "basically", "just", + "you", "know", "i", "mean", "we", "the", "a", "an", "it", "that", "this", +}) + +# Conservative defaults: HOOK_FIRST is on, but a start only ever moves a few +# seconds and never more than a quarter of the clip. +_HOOK_FIRST_DEFAULT_MAX_TRIM = 4.0 +_HOOK_FIRST_DEFAULT_MAX_FRACTION = 0.25 +# A trim smaller than this is noise; leaving the clip alone is kinder than a +# sub-frame jitter that only complicates the render. +_MIN_HOOK_TRIM = 0.2 + + +def _env_float(name, default): + """Read a float env var, falling back to ``default`` on garbage/absence.""" + import os + + raw = os.environ.get(name) + if raw is None or str(raw).strip() == "": + return default + try: + return float(raw) + except (TypeError, ValueError): + return default + + +def hook_first_enabled(): + """Whether to move clip starts onto the first spoken hook. + + ``HOOK_FIRST`` defaults ON (conservatively capped); set it to ``0`` / + ``false`` / ``no`` / ``off`` to disable the pass for A/B runs. + """ + import os + + raw = os.environ.get("HOOK_FIRST") + if raw is None: + return True + return str(raw).strip().lower() not in ("", "0", "false", "no", "off") + + +def _hook_token(raw): + """Normalise a Whisper word to a bare lowercase token. + + Words are inconsistent about a leading space (" word" vs "word") and carry + trailing punctuation ("crash!"), so both are stripped before matching. + """ + token = str(raw or "").strip().lower() + token = re.sub(r"^[^0-9a-z]+", "", token) + token = re.sub(r"[^0-9a-z]+$", "", token) + return token + + +def _is_hook_token(token): + """True when a normalised token carries one of the hook signals.""" + if not token or token in _HOOK_FILLER: + return False + if any(ch.isdigit() for ch in token): + return True + return (token in _HOOK_INTERROGATIVES + or token in _HOOK_IMPERATIVES + or token in _HOOK_NUMBERS + or token in _HOOK_CONTRAST + or token in _HOOK_STAKES) + + +def find_hook_start(words, clip_start, clip_end, min_duration=15.0, + max_trim=None, max_fraction=None): + """The strongest deterministic start for a clip, or ``None``. + + Scans the opening of ``[clip_start, clip_end]`` for the EARLIEST word that + matches a hook signal (question, imperative, number/quantity, contrast or + stakes — see the vocabularies above). Leading hesitation, silence and + filler do not match, so they fall into the trimmed wind-up. Returns the + hook word's start when it is a legal trim, else ``None`` (no change — a + clip without a clear hook is left exactly where snapping put it). + + ``words`` is the whole-video ``[{'w','s','e'}, ...]`` list (same shape + ``snap_clip_to_words`` takes). The trim is bounded three ways so the pass + can never wreck a clip: + + * ``max_trim`` seconds (env ``HOOK_FIRST_MAX_TRIM``, default 4.0) + * ``max_fraction`` of the clip's duration (env ``HOOK_FIRST_MAX_FRACTION``, + default 0.25) + * the remaining clip must still be at least ``min_duration`` seconds. + """ + try: + clip_start = float(clip_start) + clip_end = float(clip_end) + except (TypeError, ValueError): + return None + duration = clip_end - clip_start + if duration <= 0: + return None + + if max_trim is None: + max_trim = _env_float("HOOK_FIRST_MAX_TRIM", + _HOOK_FIRST_DEFAULT_MAX_TRIM) + if max_fraction is None: + max_fraction = _env_float("HOOK_FIRST_MAX_FRACTION", + _HOOK_FIRST_DEFAULT_MAX_FRACTION) + try: + max_trim = max(0.0, float(max_trim)) + max_fraction = max(0.0, float(max_fraction)) + min_duration = float(min_duration) + except (TypeError, ValueError): + return None + + cap = min(max_trim, max_fraction * duration) + if cap < _MIN_HOOK_TRIM: + return None + latest = clip_start + cap + + hook_start = None + for word in words or []: + try: + word_start = float(word.get("s", 0)) + except (AttributeError, TypeError, ValueError): + continue + if word_start < clip_start or word_start > latest: + continue + if word_start >= clip_end: + continue + if _is_hook_token(_hook_token(word.get("w"))): + if hook_start is None or word_start < hook_start: + hook_start = word_start + + if hook_start is None: + return None + trim = hook_start - clip_start + if trim < _MIN_HOOK_TRIM: + return None + if clip_end - hook_start < min_duration: + return None + return round(hook_start, 3) diff --git a/clipwright/pipeline/gemini_worker.py b/clipwright/pipeline/gemini_worker.py index f75b623..dbe57ce 100644 --- a/clipwright/pipeline/gemini_worker.py +++ b/clipwright/pipeline/gemini_worker.py @@ -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} diff --git a/clipwright/pipeline/hook_grounding.py b/clipwright/pipeline/hook_grounding.py index 12d744e..3a6bc24 100644 --- a/clipwright/pipeline/hook_grounding.py +++ b/clipwright/pipeline/hook_grounding.py @@ -24,7 +24,7 @@ import json import os from typing import Optional -SCREEN_LAYOUTS = {"screencast", "wide", "inset"} +SCREEN_LAYOUTS = {"screencast", "code", "wide", "inset"} FRAMES = int(os.environ.get("HOOK_GROUNDING_FRAMES", "3")) WIDTH = int(os.environ.get("HOOK_GROUNDING_WIDTH", "1024")) # Ignore a blip: the screen stretches must cover this share of the clip. diff --git a/clipwright/pipeline/main.py b/clipwright/pipeline/main.py index 3ce2c89..af44dc6 100644 --- a/clipwright/pipeline/main.py +++ b/clipwright/pipeline/main.py @@ -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/.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 diff --git a/clipwright/pipeline/profile_prompts.py b/clipwright/pipeline/profile_prompts.py new file mode 100644 index 0000000..2467a14 --- /dev/null +++ b/clipwright/pipeline/profile_prompts.py @@ -0,0 +1,125 @@ +"""Profile -> prompt fragments (PLAN #1, full). + +The single mapping between a channel :class:`~clipwright.pipeline.profiles.Profile` +and the text the generators read. Both generation paths use it and nothing else: + +* the clipping path (``gemini_worker.DETAIL_PROMPT_TEMPLATE``, via ``main.py``) +* the Studio path (``media/thumbnail.py``: titles, concepts, description) + +Every helper is pure and accepts ``profile=None``; a ``None`` profile returns the +empty string, so a caller that was never given a channel renders exactly the +prompt it did before profiles existed. A non-empty block ends with a single ``\\n`` +so it can be dropped onto its own line in an f-string without shifting anything +(an empty string leaves the line blank, byte-for-byte as today). + +Keep the blocks short: they are constraints on an already-long prompt, not a +second prompt. +""" + +from __future__ import annotations + +from clipwright.pipeline.profiles import Profile + +# Full sentences, keyed by the enums ``profiles.py`` validates. Kept here so a +# new enum value fails loudly (missing from the map) instead of silently +# dropping the constraint. +_KEYWORD_POSITION_TEXT = { + "start": "Put the main keyword or subject in the first 3 words", + "middle": "Put the main keyword or subject near the middle", + "end": "Put the main keyword or subject at the end", + "any": "Place the main keyword or subject wherever it reads best", +} +_NUMBER_POLICY_TEXT = { + "allow": "Numbers are allowed when they earn attention", + "avoid": "Avoid numbers unless a number is the point", + "require": "Every title must contain a concrete number", +} +_REQUIRED_SIGNAL_TEXT = { + "consequence": "Every title must carry a concrete consequence or stake", + "curiosity": "Every title must open a curiosity gap the video pays off", + "either": "Every title must carry a consequence or a curiosity gap", + "none": "", +} + + +def _quoted(items): + return "; ".join(f'"{item}"' for item in items) + + +def title_rules_block(profile: Profile | None) -> str: + """Title constraints: length, banned content, keyword/number/signal policy, tone.""" + if profile is None: + return "" + rules = profile.title_rules + lines = ["CHANNEL TITLE RULES:"] + if profile.tone: + lines.append(f"- Tone: {profile.tone}.") + lines.append( + f"- Hard maximum {rules.max_chars} characters; the payoff must land inside " + f"the first {rules.mobile_chars} (phones truncate there).") + position = _KEYWORD_POSITION_TEXT.get(rules.keyword_position) + if position: + lines.append(f"- {position}.") + signal = _REQUIRED_SIGNAL_TEXT.get(rules.required_signal) + if signal: + lines.append(f"- {signal}.") + number = _NUMBER_POLICY_TEXT.get(rules.number_policy) + if number: + lines.append(f"- {number}.") + if rules.banned_patterns: + lines.append(f"- Never use the phrases: {_quoted(rules.banned_patterns)}.") + if rules.banned_openers: + lines.append(f"- Never open a title with: {_quoted(rules.banned_openers)}.") + return "\n".join(lines) + "\n" + + +def hook_block(profile: Profile | None) -> str: + """Hook style and the patterns the channel already knows work.""" + if profile is None: + return "" + lines = [] + if profile.hook_style: + lines.append(f"- Hook style: {profile.hook_style}.") + if profile.hook_patterns: + lines.append(f"- Patterns that work for this channel: {_quoted(profile.hook_patterns)}.") + if not lines: + return "" + return "CHANNEL HOOK RULES:\n" + "\n".join(lines) + "\n" + + +def description_block(profile: Profile | None) -> str: + """Description structure, the channel's links and its tone.""" + if profile is None: + return "" + lines = [] + if profile.description_template: + template = profile.description_template.replace("\n", "\\n") + lines.append(f'- Follow this structure for the blurb: "{template}".') + if profile.links: + lines.append(f"- Include these links: {', '.join(profile.links)}.") + if profile.tone: + lines.append(f"- Tone: {profile.tone}.") + if not lines: + return "" + return "CHANNEL DESCRIPTION RULES:\n" + "\n".join(lines) + "\n" + + +def thumbnail_block(profile: Profile | None) -> str: + """Thumbnail roles, palette and whether a presenter photo is expected.""" + if profile is None: + return "" + thumb = profile.thumbnail + lines = [] + if thumb.role_order: + lines.append(f"- Concept roles, in priority order: {', '.join(thumb.role_order)}.") + if thumb.palette: + lines.append(f"- Palette: {', '.join(thumb.palette)}.") + presenter = ("available and encouraged" if thumb.presenter_photo + else "not expected; prefer objects, scenes or symbols") + lines.append(f"- Presenter photo is {presenter}.") + return "CHANNEL THUMBNAIL RULES:\n" + "\n".join(lines) + "\n" + + +def clip_rules_block(profile: Profile | None) -> str: + """The clipping path's block: hook guidance then title constraints.""" + return hook_block(profile) + title_rules_block(profile) diff --git a/clipwright/pipeline/profiles.py b/clipwright/pipeline/profiles.py new file mode 100644 index 0000000..f4983f8 --- /dev/null +++ b/clipwright/pipeline/profiles.py @@ -0,0 +1,295 @@ +"""Per-channel profiles (PLAN #1, v0). + +A profile is the machine-readable root for one channel's packaging rules: the +title constraints, hook patterns, description template and thumbnail roles that +later items (#3, #4, #6, #10) read. This v0 defines the schema, the validating +loader and the ``CHANNEL_PROFILE`` plumbing only -- nothing here changes how +titles, hooks or descriptions are generated yet. + +Files live at ``/channels/.json``. Every field is optional and +falls back to a sensible default, so a minimal ``{"language": "en"}`` file +loads. Unknown keys are ignored so a newer profile can ship ahead of the code; +known keys with the wrong type or an out-of-domain enum are refused with a +message that names the exact path. +""" + +from __future__ import annotations + +import json +import os +import re +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +from clipwright.core.paths import REPO_ROOT + +# ``/channels`` (also ``/app/channels`` in the Docker image). +CHANNELS_DIR = REPO_ROOT / "channels" +# Fallback selector used when ``load_profile`` is called without a slug. +ENV_VAR = "CHANNEL_PROFILE" + +# A slug becomes a filename under CHANNELS_DIR, so it may not contain separators +# or traversal segments. +_SLUG_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$") + +KEYWORD_POSITIONS = frozenset({"start", "middle", "end", "any"}) +NUMBER_POLICIES = frozenset({"allow", "avoid", "require"}) +REQUIRED_SIGNALS = frozenset({"consequence", "curiosity", "either", "none"}) + + +class ProfileError(ValueError): + """A channel profile is missing, unreadable or does not match the schema.""" + + +# --- typed coercion -------------------------------------------------------- + +def _require_mapping(value: Any, where: str) -> Mapping: + if not isinstance(value, Mapping): + raise ProfileError(f"{where} must be a JSON object, got {type(value).__name__}") + return value + + +def _as_str(value: Any, where: str, default: str) -> str: + if value is None: + return default + if not isinstance(value, str): + raise ProfileError(f"{where} must be a string, got {type(value).__name__}") + return value + + +def _as_optional_str(value: Any, where: str) -> str | None: + if value is None: + return None + if not isinstance(value, str): + raise ProfileError(f"{where} must be a string or null, got {type(value).__name__}") + return value + + +def _as_int(value: Any, where: str, default: int) -> int: + if value is None: + return default + # bool is an int subclass in Python; a JSON true is not a valid count. + if isinstance(value, bool) or not isinstance(value, int): + raise ProfileError(f"{where} must be an integer, got {type(value).__name__}") + return value + + +def _as_bool(value: Any, where: str, default: bool) -> bool: + if value is None: + return default + if not isinstance(value, bool): + raise ProfileError(f"{where} must be a boolean, got {type(value).__name__}") + return value + + +def _as_str_list(value: Any, where: str, default: Sequence[str]) -> list[str]: + if value is None: + return list(default) + if isinstance(value, str) or not isinstance(value, Sequence): + raise ProfileError( + f"{where} must be a JSON array of strings, got {type(value).__name__}" + ) + out: list[str] = [] + for i, item in enumerate(value): + if not isinstance(item, str): + raise ProfileError(f"{where}[{i}] must be a string, got {type(item).__name__}") + out.append(item) + return out + + +def _as_dict_list(value: Any, where: str, default: Sequence[Mapping]) -> list[dict]: + if value is None: + return [dict(d) for d in default] + if isinstance(value, str) or not isinstance(value, Sequence): + raise ProfileError( + f"{where} must be a JSON array of objects, got {type(value).__name__}" + ) + out: list[dict] = [] + for i, item in enumerate(value): + if not isinstance(item, Mapping): + raise ProfileError( + f"{where}[{i}] must be a JSON object, got {type(item).__name__}" + ) + out.append(dict(item)) + return out + + +def _as_enum(value: Any, where: str, allowed: frozenset, default: str) -> str: + if value is None: + return default + if value not in allowed: + options = ", ".join(sorted(allowed)) + raise ProfileError(f"{where} must be one of {{{options}}}, got {value!r}") + return value + + +# --- schema ---------------------------------------------------------------- + +@dataclass +class TitleRules: + """Deterministic title constraints (consumed by the #3 validator).""" + + max_chars: int = 70 + mobile_chars: int = 40 + banned_patterns: list[str] = field(default_factory=list) + keyword_position: str = "start" + number_policy: str = "allow" + required_signal: str = "either" + banned_openers: list[str] = field(default_factory=list) + + @classmethod + def from_dict(cls, data: Mapping, where: str = "title_rules") -> "TitleRules": + data = _require_mapping(data, where) + return cls( + max_chars=_as_int(data.get("max_chars"), f"{where}.max_chars", 70), + mobile_chars=_as_int(data.get("mobile_chars"), f"{where}.mobile_chars", 40), + banned_patterns=_as_str_list( + data.get("banned_patterns"), f"{where}.banned_patterns", () + ), + keyword_position=_as_enum( + data.get("keyword_position"), f"{where}.keyword_position", + KEYWORD_POSITIONS, "start", + ), + number_policy=_as_enum( + data.get("number_policy"), f"{where}.number_policy", + NUMBER_POLICIES, "allow", + ), + required_signal=_as_enum( + data.get("required_signal"), f"{where}.required_signal", + REQUIRED_SIGNALS, "either", + ), + banned_openers=_as_str_list( + data.get("banned_openers"), f"{where}.banned_openers", () + ), + ) + + +@dataclass +class ThumbnailRules: + """Thumbnail concept roles and look (consumed by #4).""" + + role_order: list[str] = field( + default_factory=lambda: ["curiosity", "emotion", "technical"] + ) + palette: list[str] = field(default_factory=list) + presenter_photo: bool = False + + @classmethod + def from_dict(cls, data: Mapping, where: str = "thumbnail") -> "ThumbnailRules": + data = _require_mapping(data, where) + return cls( + role_order=_as_str_list( + data.get("role_order"), f"{where}.role_order", + ["curiosity", "emotion", "technical"], + ), + palette=_as_str_list(data.get("palette"), f"{where}.palette", ()), + presenter_photo=_as_bool( + data.get("presenter_photo"), f"{where}.presenter_photo", False + ), + ) + + +@dataclass +class Profile: + """One channel's packaging rules.""" + + slug: str + # Human-readable display name for selectors; falls back to ``slug`` when unset. + name: str = "" + language: str = "en" + tone: str = "" + title_rules: TitleRules = field(default_factory=TitleRules) + hook_patterns: list[str] = field(default_factory=list) + hook_style: str = "" + description_template: str = "" + links: list[str] = field(default_factory=list) + thumbnail: ThumbnailRules = field(default_factory=ThumbnailRules) + default_postiz_integration_id: str | None = None + published_video_history: list[dict] = field(default_factory=list) + + @classmethod + def from_dict(cls, data: Mapping, slug: str) -> "Profile": + data = _require_mapping(data, f"profile {slug!r}") + raw_title = data.get("title_rules") + raw_thumb = data.get("thumbnail") + return cls( + slug=slug, + name=_as_str(data.get("name"), "name", ""), + language=_as_str(data.get("language"), "language", "en"), + tone=_as_str(data.get("tone"), "tone", ""), + title_rules=TitleRules.from_dict({} if raw_title is None else raw_title), + hook_patterns=_as_str_list(data.get("hook_patterns"), "hook_patterns", ()), + hook_style=_as_str(data.get("hook_style"), "hook_style", ""), + description_template=_as_str( + data.get("description_template"), "description_template", "" + ), + links=_as_str_list(data.get("links"), "links", ()), + thumbnail=ThumbnailRules.from_dict({} if raw_thumb is None else raw_thumb), + default_postiz_integration_id=_as_optional_str( + data.get("default_postiz_integration_id"), + "default_postiz_integration_id", + ), + published_video_history=_as_dict_list( + data.get("published_video_history"), "published_video_history", () + ), + ) + + +def load_profile(slug: str | None = None, channels_dir: str | os.PathLike | None = None) -> Profile: + """Load and validate ``channels/.json``. + + ``slug`` wins; when it is omitted the ``CHANNEL_PROFILE`` env var is used. + ``channels_dir`` is test/embedding seam -- it defaults to the repo's + ``channels/`` directory. + """ + resolved = slug or os.environ.get(ENV_VAR) or None + if not resolved: + raise ProfileError(f"no channel profile selected; pass a slug or set {ENV_VAR}") + if not _SLUG_RE.match(resolved): + raise ProfileError( + f"invalid channel slug {resolved!r}; expected letters, digits, '-' or '_'" + ) + + directory = Path(channels_dir) if channels_dir is not None else CHANNELS_DIR + path = directory / f"{resolved}.json" + try: + text = path.read_text(encoding="utf-8") + except FileNotFoundError: + raise ProfileError(f"channel profile not found: {path}") + except OSError as e: + raise ProfileError(f"could not read channel profile {path}: {e}") + + try: + data = json.loads(text) + except json.JSONDecodeError as e: + raise ProfileError(f"malformed JSON in {path}: {e}") + + return Profile.from_dict(data, resolved) + + +def list_profiles(channels_dir: str | os.PathLike | None = None) -> list[dict]: + """List the loadable channel profiles as ``[{"slug", "name"}]``. + + Best-effort by design: every ``channels/*.json`` that validates is included + (sorted by slug) and everything else is skipped, so one malformed profile + cannot break a selector. ``slug`` is the filename stem and ``name`` is the + profile's display name, falling back to ``slug`` when the file omits it. + ``channels_dir`` is the same test/embedding seam as :func:`load_profile`. + """ + directory = Path(channels_dir) if channels_dir is not None else CHANNELS_DIR + if not directory.is_dir(): + return [] + + out: list[dict] = [] + for path in sorted(directory.glob("*.json")): + slug = path.stem + if not _SLUG_RE.match(slug): + continue + try: + profile = load_profile(slug, channels_dir=directory) + except ProfileError: + continue + out.append({"slug": slug, "name": profile.name or slug}) + return out diff --git a/clipwright/tools/verify_code_layout.py b/clipwright/tools/verify_code_layout.py new file mode 100644 index 0000000..eed3ea0 --- /dev/null +++ b/clipwright/tools/verify_code_layout.py @@ -0,0 +1,169 @@ +"""Calibration tool for the CODE/TERMINAL layout. + +Usage (from the repo root): + + python -m clipwright.tools.verify_code_layout path/to/recording.mp4 \ + --start 12.0 --duration 8 --out-dir output/code_layout + +It forces the layout on (ignoring ``CODE_LAYOUT``), detects the pane, prints +pane / confidence / mode, writes: + + - ``debug_bands.png`` — a schematic of the 9:16 output with the code band and + the caption reserve marked; + - ``still.png`` — a real render through ``code_filtergraph`` at ``--start``. + +Exit codes: 0 on a detected pane and a rendered still; 1 when nothing detects +(so a corpus sweep can flag misses); 2 when cv2 is unavailable. + +The detection thresholds in ``code_layout`` are estimates from first +principles. Run this across a set of real 1440p IDE and terminal recordings and +tune ``CODE_*`` from what actually lands here. +""" +import argparse +import os +import subprocess +import sys + +DEFAULT_OUT = "output/code_layout" + + +def _parse_args(argv): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("video", help="path to the source recording") + parser.add_argument("--start", type=float, default=0.0, + help="segment start in seconds") + parser.add_argument("--duration", type=float, default=6.0, + help="seconds of active-line tracking to sample") + parser.add_argument("--samples", type=int, default=12, + help="frames sampled for pane detection") + parser.add_argument("--out-w", type=int, default=1080) + parser.add_argument("--out-h", type=int, default=1920) + parser.add_argument("--out-dir", default=DEFAULT_OUT) + parser.add_argument("--no-follow", action="store_true", + help="skip active-line tracking (static window)") + return parser.parse_args(argv) + + +def _draw_bands(path, pane, out_w, out_h, graph): + """Schematic of the output: backdrop, code band, caption reserve.""" + import cv2 + import numpy as np + + canvas = np.full((out_h, out_w, 3), 32, dtype=np.uint8) + content_h, caption_h = _bands(out_h) + scale = out_w / float(pane["w"]) + scaled_h = min(content_h, int(round(pane["h"] * scale))) + y_off = max(0, (content_h - scaled_h) // 2) + + cv2.rectangle(canvas, (0, y_off), (out_w - 1, y_off + scaled_h), + (40, 160, 40), thickness=-1) + cv2.rectangle(canvas, (0, out_h - caption_h), (out_w - 1, out_h - 1), + (160, 90, 40), thickness=-1) + cv2.putText(canvas, f"pane {pane['w']}x{pane['h']} @ {pane['x']},{pane['y']}", + (16, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2) + cv2.putText(canvas, f"code band h={scaled_h}", + (16, y_off + max(30, scaled_h // 2)), + cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2) + cv2.putText(canvas, "caption reserve", + (16, out_h - caption_h + max(30, caption_h // 2)), + cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 2) + if "sendcmd" in graph: + cv2.putText(canvas, "sendcmd follow ON", + (16, out_h - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, + (80, 220, 255), 2) + cv2.imwrite(path, canvas) + + +def _bands(out_h): + from clipwright.layouts import code_layout + return code_layout.code_bands(out_h) + + +def _render_still(video, start, graph, out_path): + cmd = [ + "ffmpeg", "-y", "-loglevel", "error", + "-ss", f"{start:.4f}", "-i", video, + "-frames:v", "1", + "-filter_complex", graph, "-map", "[v]", + out_path, + ] + proc = subprocess.run(cmd, capture_output=True, text=True) + if proc.returncode != 0: + print(f"❌ ffmpeg failed:\n{proc.stderr}") + return False + return os.path.exists(out_path) and os.path.getsize(out_path) > 0 + + +def main(argv=None): + args = _parse_args(argv if argv is not None else sys.argv[1:]) + try: + import cv2 # noqa: F401 (presence check only) + except ImportError: + print("❌ OpenCV (cv2) is required to run this tool.") + return 2 + + from clipwright.layouts import code_layout + code_layout.ENABLED = True + code_layout.FOLLOW_ENABLED = True + + if not os.path.exists(args.video): + print(f"❌ No such video: {args.video}") + return 1 + + os.makedirs(args.out_dir, exist_ok=True) + + pane = code_layout.detect_code_pane(args.video, samples=args.samples) + if pane is None: + print("❌ No code pane detected — nothing to render. " + "Tune CODE_PANE_MIN_* / CODE_EDGE_DENSITY / CODE_STABILITY_*.") + return 1 + + print(f"✅ Pane: x={pane['x']} y={pane['y']} w={pane['w']} h={pane['h']} " + f"({pane['w']}x{pane['h']})") + print(f" mode={pane['mode']} confidence={pane['confidence']:.2f} " + f"frame={pane['frame_w']}x{pane['frame_h']}") + + # Mirror reframe_v2: if the text column is still wider than the readable + # scale allows, crop it to out_w / MIN_SCALE rather than falling back. + max_w = max(2, int(args.out_w / code_layout.MIN_SCALE)) + clamped = code_layout.clamp_pane_width(pane, max_w) + if clamped[2] != pane["w"]: + print(f" clamped text column {pane['w']} -> {clamped[2]}px " + f"(CODE_MIN_SCALE={code_layout.MIN_SCALE})") + pane = dict(pane, x=clamped[0], y=clamped[1], w=clamped[2], h=clamped[3]) + print(f" scale: {args.out_w / float(pane['w']):.2f}") + + follow = None + if not args.no_follow: + series = code_layout.active_line_series( + args.video, pane, args.start, args.start + args.duration) + if series: + # code_filtergraph expects timestamps relative to the segment start. + follow = [(t - args.start, y) for t, y in series] + print(f" follow: {len(follow)} points over " + f"{follow[0][0]:.1f}-{follow[-1][0]:.1f}s") + else: + print(" follow: no reliable active-line series (static window)") + + graph = code_layout.code_filtergraph(pane, args.out_w, args.out_h, + follow=follow) + if graph is None: + scale = args.out_w / float(max(1, pane["w"])) + print(f"❌ Scale {scale:.2f} < CODE_MIN_SCALE " + f"({code_layout.MIN_SCALE}) — this clip falls back to " + f"SCREENCAST/WIDE.") + return 1 + + debug_path = os.path.join(args.out_dir, "debug_bands.png") + still_path = os.path.join(args.out_dir, "still.png") + _draw_bands(debug_path, pane, args.out_w, args.out_h, graph) + if not _render_still(args.video, args.start, graph, still_path): + return 1 + + print(f"🖼️ wrote {debug_path}") + print(f"🖼️ wrote {still_path}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index e2b79b6..650482a 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -159,14 +159,23 @@ const postizHeaders = (key, url) => { // Older builds defaulted to a maintainer-hosted Postiz instance and persisted // it to localStorage on mount, so an upgrade could silently keep sending a -// user's API key to someone else's server. Recognize that retired default and -// treat it as unset. The host is assembled from parts so no live reference to -// it remains in the source. +// user's API key to a server they never chose. Retire that one legacy value +// ONCE (guarded by a marker) instead of on every read: blanking it on each load +// also threw away a URL the user deliberately saved — a self-hoster's own +// instance can legitimately live on that host — and forced them to retype it +// every session. The host is assembled from parts so no live reference to it +// remains in the source. const RETIRED_POSTIZ_HOST = ['postiz', 'pbento', 'pt'].join('.'); +const POSTIZ_URL_RETIRED_KEY = 'postiz_url_retired_v1'; const normalizeStoredPostizUrl = (url) => { const base = String(url || '').trim().replace(/\/$/, ''); if (!base) return ''; - return base === `https://${RETIRED_POSTIZ_HOST}` ? '' : base; + let retired = false; + try { + retired = localStorage.getItem(POSTIZ_URL_RETIRED_KEY) === '1'; + localStorage.setItem(POSTIZ_URL_RETIRED_KEY, '1'); + } catch (_) { /* storage unavailable: nothing to migrate */ } + return !retired && base === `https://${RETIRED_POSTIZ_HOST}` ? '' : base; }; const SESSION_KEY = 'clipwright_session'; @@ -255,6 +264,9 @@ function App() { const [downloadingAll, setDownloadingAll] = useState(false); // Pre-flight quality gate: { info: {max_height, min_height, cookies_invalid}, data } const [qualityGate, setQualityGate] = useState(null); + // True while the optional cadence handoff ZIP is being uploaded, before the + // process request is sent. Drives the small status line in the left panel. + const [handoffUploading, setHandoffUploading] = useState(false); const [logs, setLogs] = useState([]); // When each server log line arrived (epoch s, parallel to logs), from /api/status. const [logTimes, setLogTimes] = useState([]); @@ -673,8 +685,45 @@ function App() { auto_hook_style: data.autoHook ? (data.autoHookStyle || 'pill') : null, // 'auto' is the server default, so only a deliberate choice travels. layouts: data.layout && data.layout !== 'auto' ? data.layout : null, + // Channel profile slug (channels/.json). Absent = no profile, so + // the default request stays byte-identical to the pre-feature one. + channel: data.channel || null, }; + // Optional cadence handoff bundle: reserve a slot, PUT the ZIP, then pass + // its id to /api/process. A failure throws and is caught below, aborting + // the job rather than silently re-transcribing the master. + let handoffId = null; + if (data.handoffFile) { + setHandoffUploading(true); + setLogs((l) => [...l, `Uploading handoff bundle (${data.handoffFile.name})…`]); + try { + const createRes = await apiFetch('/api/uploads', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ filename: data.handoffFile.name, kind: 'handoff' }), + }); + if (!createRes.ok) throw new Error(`Handoff upload failed: ${readableError(await createRes.text())}`); + const slot = await createRes.json(); + if (!slot?.upload_url) throw new Error('Handoff upload failed: the server returned no upload URL.'); + const putRes = await apiFetch(slot.upload_url, { + method: slot.method || 'PUT', + headers: { 'Content-Type': 'application/zip' }, + body: data.handoffFile, + }); + if (!putRes.ok) throw new Error(`Handoff upload failed: ${readableError(await putRes.text())}`); + const putData = await putRes.json().catch(() => ({})); + handoffId = putData.upload_id || slot.upload_id || null; + if (!handoffId) throw new Error('Handoff upload failed: the server returned no upload id.'); + setLogs((l) => [...l, 'Handoff bundle attached — transcription will be skipped.']); + } finally { + setHandoffUploading(false); + } + } + // Only travels when a bundle was attached, so the default request is + // byte-identical to today's. + if (handoffId) advanced.handoff_id = handoffId; + if (data.type === 'url') { headers['Content-Type'] = 'application/json'; body = JSON.stringify({ @@ -1200,6 +1249,13 @@ function App() { + {handoffUploading && ( +
+ + uploading handoff bundle… +
+ )} + {/* Video Preview */} {processingMedia && ( long-form bridge (PLAN #6). The related-video link and comment +// pinning are Studio-UI only, so this panel always carries the manual steps: +// it never pretends the server can set them. +// +// Copy it? Use the copy buttons. Post the first comment automatically? Only +// when you click it, and only on a server with the YouTube Data API wired up. + +// Accept a full YouTube URL or a bare id and return just the id. The published +// Short's id is what the comment endpoint needs; people usually have the URL. +function videoIdFrom(raw) { + const value = String(raw || '').trim(); + if (!value) return ''; + const urlMatch = value.match(/(?:v=|\/shorts\/|youtu\.be\/|\/embed\/)([A-Za-z0-9_-]{6,})/); + if (urlMatch) return urlMatch[1]; + const bare = value.match(/^([A-Za-z0-9_-]{6,})$/); + return bare ? bare[1] : value; +} + +export default function BridgeModal({ isOpen, onClose, jobId, clipIndex }) { + const [data, setData] = useState(null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + const [copied, setCopied] = useState(null); + + // Checked-off Studio steps, remembered per clip so closing the sheet while + // working through the manual steps doesn't lose your place. + const storageKey = `cw_bridge_check_${jobId}_${clipIndex}`; + const [checkedSteps, setCheckedSteps] = useState({}); + + const [videoId, setVideoId] = useState(''); + const [posting, setPosting] = useState(false); + const [postStatus, setPostStatus] = useState(null); + + useEffect(() => { + if (!isOpen) return undefined; + let cancelled = false; + + setLoading(true); + setError(null); + setData(null); + setPostStatus(null); + setVideoId(''); + try { + setCheckedSteps(JSON.parse(localStorage.getItem(storageKey)) || {}); + } catch { + setCheckedSteps({}); + } + + apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge`) + .then(async (res) => { + if (!res.ok) { + let detail = ''; + const text = await res.text().catch(() => ''); + try { + const j = JSON.parse(text); + if (typeof j.detail === 'string') detail = j.detail; + } catch { /* keep the raw body */ } + throw new Error(detail || `Could not load the bridge (${res.status}).`); + } + return res.json(); + }) + .then((payload) => { if (!cancelled) setData(payload); }) + .catch((e) => { if (!cancelled) setError(e.message || 'Could not load the bridge.'); }) + .finally(() => { if (!cancelled) setLoading(false); }); + + return () => { cancelled = true; }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isOpen, jobId, clipIndex]); + + const handleCopy = async (field, text) => { + try { + await navigator.clipboard.writeText(text || ''); + setCopied(field); + setTimeout(() => setCopied(null), 2000); + } catch { + // clipboard unavailable — silent + } + }; + + const toggleStep = (i) => { + setCheckedSteps((prev) => { + const next = { ...prev, [i]: !prev[i] }; + try { localStorage.setItem(storageKey, JSON.stringify(next)); } catch { /* storage unavailable */ } + return next; + }); + }; + + const handlePostComment = async () => { + const vid = videoIdFrom(videoId); + if (!vid) return; + setPosting(true); + setPostStatus(null); + try { + const res = await apiFetch(`/api/clip/${jobId}/${clipIndex}/bridge/comment`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ video_id: vid, text: data?.first_comment || undefined }), + }); + if (!res.ok) { + let detail = ''; + const text = await res.text().catch(() => ''); + try { + const j = JSON.parse(text); + if (typeof j.detail === 'string') detail = j.detail; + } catch { /* keep the raw body */ } + // A 400 here almost always means the YouTube integration is not + // configured; say that plainly and point at the manual route. + const fallback = res.status === 400 + ? "This server can't post comments yet — the YouTube Data API isn't set up. Copy the comment above and post it in Studio instead." + : `Could not post the comment (${res.status}).`; + setPostStatus({ ok: false, msg: detail || fallback }); + return; + } + await res.json().catch(() => ({})); + setPostStatus({ ok: true, msg: 'Comment posted. Open YouTube Studio and pin it — pinning stays manual.' }); + } catch (e) { + setPostStatus({ ok: false, msg: e.message || 'Could not post the comment.' }); + } finally { + setPosting(false); + } + }; + + // The endpoint reports whether comment posting is available on this server. + // An older/absent field is treated as "try it" — a 400 is handled above. + const configured = data ? data.comment_api_configured !== false : true; + const canPostComment = configured && !!videoId.trim() && !!data?.first_comment; + + return ( + + {loading && ( +
+ loading bridge… +
+ )} + + {!loading && error && ( +
+ + {error} +
+ )} + + {!loading && !error && data && ( +
+

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

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

no checklist saved for this clip.

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

+ {data.description_bridge} +

+ ) : ( +

+ no description copy generated for this clip. +

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

+ {data.first_comment} +

+ ) : ( +

+ no first comment generated for this clip. +

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

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

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

+ related-video link + pin: Studio only +

+
+
+ )} +
+ ); +} diff --git a/dashboard/src/components/MediaInput.jsx b/dashboard/src/components/MediaInput.jsx index 38c1891..564dd8f 100644 --- a/dashboard/src/components/MediaInput.jsx +++ b/dashboard/src/components/MediaInput.jsx @@ -1,5 +1,5 @@ import React, { useState, useEffect, useRef } from 'react'; -import { Link2, Upload, FileVideo, X, Info, Loader2, ChevronDown } from 'lucide-react'; +import { Link2, Upload, FileVideo, X, Info, Loader2, ChevronDown, Paperclip, FileArchive } from 'lucide-react'; import { track } from '../lib/analytics'; import { getApiUrl } from '../config'; @@ -61,6 +61,18 @@ export default function MediaInput({ onProcess, isProcessing }) { const [layout, setLayout] = useState(() => { try { return localStorage.getItem('cw_layout') || 'auto'; } catch { return 'auto'; } }); + // Channel profile (channels/.json on the server): tunes how the AI + // writes titles, hooks and the description, and how it art-directs the + // thumbnail. Per job and off by default, so nothing changes for anyone who + // does not use profiles. Fetched from GET /api/channels; when that list is + // empty or unreachable the selector simply does not render. + const [channels, setChannels] = useState([]); + const [channel, setChannel] = useState('none'); + // Cadence handoff bundle (optional): cadence's ZIP with the manifest and + // transcript for the master. Attached to a local-file job so the pipeline + // skips transcription. It is not sent with the video form — the parent + // uploads it to its own slot on submit and passes back handoff_id. + const [handoffFile, setHandoffFile] = useState(null); const infoRef = useRef(null); // Close the compatibility popover on any outside click. @@ -99,6 +111,22 @@ export default function MediaInput({ onProcess, isProcessing }) { .catch(() => {}); }, []); + // Channel profiles available on this install. A missing route, an empty + // directory or a network error all leave the list empty, which keeps the + // selector hidden — profiles are opt-in and never block a job. + useEffect(() => { + let cancelled = false; + fetch(getApiUrl('/api/channels')) + .then((r) => (r.ok ? r.json() : null)) + .then((data) => { + if (cancelled || !data) return; + const list = Array.isArray(data.channels) ? data.channels : []; + setChannels(list.filter((c) => c && c.slug)); + }) + .catch(() => {}); + return () => { cancelled = true; }; + }, []); + // A link pasted in the landing hero: preload it here so the user picks up // where they left off. Not auto-submitted — the rights attestation below // has to be ticked by the user. @@ -124,6 +152,9 @@ export default function MediaInput({ onProcess, isProcessing }) { autoHook, autoHookStyle, layout, + // 'none' = no profile; only a real slug travels, so the default + // request stays byte-identical to the pre-feature one. + channel: channel === 'none' ? null : channel, }; try { localStorage.setItem('cw_auto_hook', autoHook ? '1' : '0'); @@ -133,7 +164,9 @@ export default function MediaInput({ onProcess, isProcessing }) { if (mode === 'url' && url) { onProcess({ type: 'url', payload: url, acknowledged: true, outputFormat, ...advanced }); } else if (mode === 'file' && file && !fileTooShort) { - onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat, ...advanced }); + // The handoff bundle only travels with a local master: it is the + // edition cadence cut from that same file. + onProcess({ type: 'file', payload: file, acknowledged: true, outputFormat, handoffFile: handoffFile || null, ...advanced }); } }; @@ -255,6 +288,49 @@ export default function MediaInput({ onProcess, isProcessing }) { )} + {/* Cadence handoff bundle — local file jobs only. Optional: + without it nothing changes. With it, the parent uploads the + ZIP to its own slot and the pipeline skips transcription. */} + {mode === 'file' && ( +
+ {handoffFile ? ( +
+ + + {handoffFile.name} + + skips transcription · must match the master's edit + + + +
+ ) : ( + + )} +
+ )} + {/* Output format selector */}

Output format

@@ -291,6 +367,32 @@ export default function MediaInput({ onProcess, isProcessing }) {
+ {/* Channel profile — only rendered when the install has profiles, + so an empty list or a failed fetch leaves no trace. Tunes the + packaging the AI writes for a job: title, hook, description + and thumbnail. Defaults to no profile. */} + {channels.length > 0 && ( +
+
+

channel profile

+ +
+

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

+
+ )} + {/* Advanced generation controls — collapsed by default; blank = AI decides */}
diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index bfcb038..854ae83 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -4,6 +4,7 @@ import { getApiUrl } from '../config'; import { apiFetch } from '../lib/api'; import SubtitleModal from './SubtitleModal'; import HookModal from './HookModal'; +import BridgeModal from './BridgeModal'; import Modal from './ui/Modal'; import { renderInBrowser } from '../lib/renderInBrowser'; @@ -25,17 +26,26 @@ const PlatformIcon = ({ identifier, size = 16 }) => { return ; }; -// DD/MM/YYYY + HH:MM parsed into a local Date, with explicit range checks so -// 31/02/2026 is rejected instead of silently rolling over to March. +// Today as YYYY-MM-DD in the user's own timezone, for the date input's `min`. +// Built from local parts (not toISOString, which would shift the day across the +// UTC boundary for users west of Greenwich). +function todayInputValue() { + const n = new Date(); + return `${n.getFullYear()}-${String(n.getMonth() + 1).padStart(2, '0')}-${String(n.getDate()).padStart(2, '0')}`; +} + +// YYYY-MM-DD (a native date picker's value) + HH:MM parsed into a local Date, +// with explicit range checks so 2026-02-31 is rejected instead of silently +// rolling over to March. function parseSchedule(dateStr, timeStr) { const d = String(dateStr || '').trim(); const t = String(timeStr || '').trim(); - if (!d || !t) return { error: 'Enter both a date (dd/mm/yyyy) and a time.' }; - const dm = d.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/); - if (!dm) return { error: 'Date must be in dd/mm/yyyy format.' }; - const day = Number(dm[1]); + if (!d || !t) return { error: 'Pick a date and a time.' }; + const dm = d.match(/^(\d{4})-(\d{2})-(\d{2})$/); + if (!dm) return { error: 'Date must be in yyyy-mm-dd format.' }; + const year = Number(dm[1]); const month = Number(dm[2]); - const year = Number(dm[3]); + const day = Number(dm[3]); if (month < 1 || month > 12) return { error: 'Month must be between 01 and 12.' }; if (day < 1 || day > 31) return { error: 'Day must be between 01 and 31.' }; const tm = t.match(/^(\d{1,2}):(\d{2})$/); @@ -214,6 +224,7 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g const [isSubtitling, setIsSubtitling] = useState(false); const [isHooking, setIsHooking] = useState(false); const [showHookModal, setShowHookModal] = useState(false); + const [showBridgeModal, setShowBridgeModal] = useState(false); const [editError, setEditError] = useState(null); const [clipDuration, setClipDuration] = useState(() => { @@ -924,6 +935,15 @@ export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, g {isHooking ? 'saving…' : 'edit hook'} + +