Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.
Python ai-toolsauto-captionscaptionscliffmpegmcpmcp-serveropusclip-alternativepodcast-clipspodcastsshortform-videovertical-videowhisper
Add `studio` command: cut a fragment + Remotion intro/outro bookends (#4)
RIKI0afe2246c8cb
diff --git a/backend/cli.py b/backend/cli.pyindex aa25ffe..3b8cd90 100644--- a/backend/cli.py+++ b/backend/cli.py@@ -302,6 +302,67 @@ def _should_enter_post_render_loop(config: dict, interrupted: bool, results: lisreturn bool(config.get("post_render_review", False) or (interrupted and _has_successful_results(results)))+def cmd_studio(args):+ """Cut a fragment + wrap it with Remotion intro/outro bookends.++ Thin wrapper around scripts/clip_studio.py (which orchestrates the+ fragment render, bookend renders, and the concat). Runs it as a+ subprocess with this same interpreter so the venv is reused.+ """+ if not getattr(args, "save_brand", False) and not args.paragraph and (args.start is None or args.end is None):+ print("Error: provide either --start and --end, or --paragraph \"text\"", file=sys.stderr)+ sys.exit(1)++ project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+ script = os.path.join(project_root, "scripts", "clip_studio.py")+ if not os.path.exists(script):+ print(f"Error: clip_studio.py not found at {script}", file=sys.stderr)+ sys.exit(1)++ # When just saving the brand, no video is needed; pass a placeholder the+ # script ignores because --save-brand returns before touching the video.+ video_arg = os.path.abspath(args.video) if args.video else "_brand_only_"+ cmd = [sys.executable, script, video_arg]+ if getattr(args, "save_brand", False):+ cmd += ["--save-brand"]+ if args.start is not None:+ cmd += ["--start", str(args.start)]+ if args.end is not None:+ cmd += ["--end", str(args.end)]+ if args.paragraph:+ cmd += ["--paragraph", args.paragraph]+ if args.language:+ cmd += ["--language", args.language]+ cmd += [+ "--caption-style", args.caption_style,+ "--crop", args.crop,+ "--intro-seconds", str(args.intro_seconds),+ "--outro-seconds", str(args.outro_seconds),+ ]+ if args.outro_title is not None:+ cmd += ["--outro-title", args.outro_title]+ if args.platforms is not None:+ cmd += ["--platforms", args.platforms]+ if args.accent is not None:+ cmd += ["--accent", args.accent]+ if args.bg is not None:+ cmd += ["--bg", args.bg]+ if args.intro_title:+ cmd += ["--intro-title", args.intro_title]+ if args.handle:+ cmd += ["--handle", args.handle]+ if args.output:+ cmd += ["--output", os.path.abspath(args.output)]+ if args.no_intro:+ cmd += ["--no-intro"]+ if args.no_outro:+ cmd += ["--no-outro"]++ import subprocess+ rc = subprocess.run(cmd).returncode+ sys.exit(rc)++def cmd_process(args):"""Full auto pipeline: transcribe → suggest → export."""from services.clip_generator import generate_clip@@ -3181,6 +3242,29 @@ def main():proc.add_argument("--review-each", action="store_true", help="Review each rendered clip interactively")proc.add_argument("--post-review", action="store_true", help="Open the post-render review loop after export")+ # ── studio ──+ studio = sub.add_parser("studio", help="Cut a fragment + add Remotion intro/outro (follow-us) bookends")+ studio.add_argument("video", nargs="?", default=None, help="Path to the source video (omit only with --save-brand)")+ studio.add_argument("--start", type=float, help="Fragment start (seconds)")+ studio.add_argument("--end", type=float, help="Fragment end (seconds)")+ studio.add_argument("--paragraph", help="Find the fragment by matching this text in the transcript")+ studio.add_argument("--language", help="Transcription language (e.g. es). Auto-detect if omitted.")+ studio.add_argument("--caption-style", choices=["hormozi", "karaoke", "subtle", "branded"], default="hormozi")+ studio.add_argument("--crop", choices=["center", "face", "speaker", "speaker-hardcut"], default="face")+ studio.add_argument("-o", "--output", help="Final output path")+ studio.add_argument("--intro-title", help="Intro headline (default: derived from first words)")+ studio.add_argument("--outro-title", default=None)+ studio.add_argument("--handle", help="Handle shown on cards, e.g. @yourbrand")+ studio.add_argument("--platforms", default=None)+ studio.add_argument("--intro-seconds", type=float, default=2.0)+ studio.add_argument("--outro-seconds", type=float, default=3.0)+ studio.add_argument("--accent", default=None)+ studio.add_argument("--bg", default=None)+ studio.add_argument("--no-intro", action="store_true")+ studio.add_argument("--no-outro", action="store_true")+ studio.add_argument("--save-brand", action="store_true",+ help="Save handle/platforms/outro-title/accent/bg as the default brand and exit")+# ── presets ──pre = sub.add_parser("presets", help="Manage presets")pre_sub = pre.add_subparsers(dest="presets_action")@@ -3368,6 +3452,8 @@ def main():if not getattr(args, "no_banner", False):print()cmd_process(args)+ elif args.command == "studio":+ cmd_studio(args)elif args.command == "thumbnails":cmd_thumbnails(args)elif args.command == "swap-thumbnail":diff --git a/remotion/render-bookend.mjs b/remotion/render-bookend.mjsnew file mode 100644index 0000000..ee6c7df--- /dev/null+++ b/remotion/render-bookend.mjs@@ -0,0 +1,118 @@+#!/usr/bin/env node+/**+ * Render an intro or outro "bookend" card via Remotion, with a silent audio+ * track so it concatenates cleanly with the main clip.+ *+ * Usage:+ * node remotion/render-bookend.mjs \+ * --mode outro \+ * --title "Follow for more" \+ * --handle "@yourbrand" \+ * --platforms tiktok,instagram,youtube,x \+ * --seconds 3 \+ * --output /path/to/outro.mp4 \+ * [--bg "#0B0B0F"] [--accent "#FFE000"] [--fps 30] [--width 1080] [--height 1920]+ */++import { bundle } from "@remotion/bundler";+import { renderMedia, selectComposition } from "@remotion/renderer";+import path from "path";+import fs from "fs";+import os from "os";+import crypto from "crypto";+import { spawnSync } from "child_process";+import { fileURLToPath } from "url";++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const PROJECT_ROOT = path.resolve(__dirname, "..");+const CACHE_DIR = path.join(PROJECT_ROOT, ".podcli", "cache", "remotion-bundle");+const ENTRY_POINT = path.join(__dirname, "src", "index.ts");++function parseArgs() {+ const args = process.argv.slice(2);+ const opts = {};+ for (let i = 0; i < args.length; i++) {+ if (args[i].startsWith("--") && i + 1 < args.length) {+ opts[args[i].replace(/^--/, "")] = args[i + 1];+ i++;+ }+ }+ return opts;+}++async function getBundle() {+ // Reuse podcli's cached bundle if present; otherwise build fresh.+ if (fs.existsSync(path.join(CACHE_DIR, "index.html"))) return CACHE_DIR;+ return await bundle({ entryPoint: ENTRY_POINT, outDir: CACHE_DIR });+}++async function main() {+ const opts = parseArgs();+ if (!opts.mode || !opts.output) {+ console.error("Usage: render-bookend.mjs --mode intro|outro --title <t> --output <path> [--handle --platforms --seconds --bg --accent]");+ process.exit(1);+ }++ const fps = parseInt(opts.fps || "30", 10);+ const width = parseInt(opts.width || "1080", 10);+ const height = parseInt(opts.height || "1920", 10);+ const seconds = parseFloat(opts.seconds || "3");+ const durationInFrames = Math.round(seconds * fps);+ const platforms = (opts.platforms || "tiktok,instagram,youtube,x")+ .split(",").map((s) => s.trim()).filter(Boolean);++ const inputProps = {+ bookendMode: opts.mode,+ bookendTitle: opts.title || (opts.mode === "outro" ? "Follow for more" : ""),+ bookendHandle: opts.handle || undefined,+ bookendPlatforms: platforms,+ bookendBg: opts.bg || "#0B0B0F",+ bookendAccent: opts.accent || "#FFE000",+ };++ const bundleLocation = await getBundle();+ const composition = await selectComposition({ serveUrl: bundleLocation, id: "Bookend", inputProps });++ const seed = `${path.resolve(opts.output)}:${process.pid}`;+ const id = crypto.createHash("md5").update(seed).digest("hex").slice(0, 12);+ const silentVideo = path.join(os.tmpdir(), `bookend_${id}.mp4`);++ console.log(`Bookend: ${opts.mode}, "${inputProps.bookendTitle}", ${platforms.join("+")}, ${durationInFrames}f`);++ await renderMedia({+ composition: { ...composition, durationInFrames, fps, width, height },+ serveUrl: bundleLocation,+ codec: "h264",+ outputLocation: silentVideo,+ inputProps,+ crf: 16,+ concurrency: Math.max(2, Math.min(os.cpus().length, 8)),+ });++ // Add a silent stereo audio track so concat/crossfade with the main clip+ // (which has audio) doesn't fail on a missing audio stream.+ const mux = spawnSync(+ "ffmpeg",+ [+ "-y",+ "-i", silentVideo,+ "-f", "lavfi",+ "-i", "anullsrc=channel_layout=stereo:sample_rate=44100",+ "-c:v", "copy",+ "-c:a", "aac",+ "-b:a", "192k",+ "-ar", "44100",+ "-shortest",+ path.resolve(opts.output),+ ],+ { stdio: "ignore", timeout: 60000 }+ );+ if (mux.status !== 0) {+ throw new Error(`ffmpeg failed to add silent audio track (exit ${mux.status})`);+ }+ try { fs.unlinkSync(silentVideo); } catch {}++ console.log(`OK ${opts.output}`);+}++main().catch((e) => { console.error("Bookend render failed:", e?.message || e); process.exit(1); });diff --git a/remotion/src/Bookend.tsx b/remotion/src/Bookend.tsxnew file mode 100644index 0000000..4ae4702--- /dev/null+++ b/remotion/src/Bookend.tsx@@ -0,0 +1,180 @@+import React from "react";+import { AbsoluteFill, interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";++export interface BookendProps {+ mode: "intro" | "outro";+ title: string; // intro: the headline; outro: the call-to-action ("Follow for more")+ handle?: string; // e.g. "@yourbrand"+ platforms: string[]; // subset of: tiktok, instagram, youtube, x+ bg?: string; // background color+ accent?: string; // accent color (active word / underline / icons)+}++const FONT = "'DM Sans', sans-serif";++// --- Recognizable social glyphs as inline SVG (monochrome, fill=currentColor) ---+const Glyph: React.FC<{ name: string; size: number; color: string }> = ({ name, size, color }) => {+ const common = { width: size, height: size, viewBox: "0 0 24 24", fill: color } as const;+ switch (name) {+ case "tiktok":+ return (+ <svg {...common}>+ <path d="M16.6 5.82A4.28 4.28 0 0 1 15.54 3h-3.1v12.4a2.59 2.59 0 1 1-2.59-2.59c.27 0 .53.04.78.12V9.77a5.7 5.7 0 0 0-.78-.05A5.69 5.69 0 1 0 15.54 15.4V9.01a7.34 7.34 0 0 0 4.3 1.38V7.3a4.28 4.28 0 0 1-3.24-1.48z" />+ </svg>+ );+ case "instagram":+ return (+ <svg {...common}>+ <path d="M12 2.16c3.2 0 3.58.01 4.85.07 1.17.05 1.8.25 2.23.41.56.22.96.48 1.38.9.42.42.68.82.9 1.38.16.42.36 1.06.41 2.23.06 1.27.07 1.65.07 4.85s-.01 3.58-.07 4.85c-.05 1.17-.25 1.8-.41 2.23-.22.56-.48.96-.9 1.38-.42.42-.82.68-1.38.9-.42.16-1.06.36-2.23.41-1.27.06-1.65.07-4.85.07s-3.58-.01-4.85-.07c-1.17-.05-1.8-.25-2.23-.41a3.7 3.7 0 0 1-1.38-.9 3.7 3.7 0 0 1-.9-1.38c-.16-.42-.36-1.06-.41-2.23C2.17 15.58 2.16 15.2 2.16 12s.01-3.58.07-4.85c.05-1.17.25-1.8.41-2.23.22-.56.48-.96.9-1.38.42-.42.82-.68 1.38-.9.42-.16 1.06-.36 2.23-.41C8.42 2.17 8.8 2.16 12 2.16zm0 3.68A6.16 6.16 0 1 0 18.16 12 6.16 6.16 0 0 0 12 5.84zm0 10.16A4 4 0 1 1 16 12a4 4 0 0 1-4 4zm6.4-10.4a1.44 1.44 0 1 1-1.44-1.44 1.44 1.44 0 0 1 1.44 1.44z" />+ </svg>+ );+ case "youtube":+ return (+ <svg {...common}>+ <path d="M23.5 6.2a3 3 0 0 0-2.1-2.1C19.5 3.5 12 3.5 12 3.5s-7.5 0-9.4.6A3 3 0 0 0 .5 6.2 31 31 0 0 0 0 12a31 31 0 0 0 .5 5.8 3 3 0 0 0 2.1 2.1c1.9.6 9.4.6 9.4.6s7.5 0 9.4-.6a3 3 0 0 0 2.1-2.1A31 31 0 0 0 24 12a31 31 0 0 0-.5-5.8zM9.6 15.6V8.4l6.3 3.6z" />+ </svg>+ );+ case "x":+ return (+ <svg {...common}>+ <path d="M18.9 2H22l-7.1 8.1L23.3 22h-6.6l-5.2-6.8L5.6 22H2.5l7.6-8.7L1 2h6.8l4.7 6.2zm-1.1 18h1.8L7.3 3.9H5.4z" />+ </svg>+ );+ default:+ return null;+ }+};++const PLATFORM_LABEL: Record<string, string> = {+ tiktok: "TikTok",+ instagram: "Instagram",+ youtube: "YouTube",+ x: "X",+};++export const Bookend: React.FC<BookendProps> = ({+ mode,+ title,+ handle,+ platforms,+ bg = "#0B0B0F",+ accent = "#FFE000",+}) => {+ const frame = useCurrentFrame();+ const { fps, width, height } = useVideoConfig();++ // Title slides up + fades in+ const titleProgress = spring({ frame, fps, config: { damping: 200 }, durationInFrames: Math.round(fps * 0.6) });+ const titleY = interpolate(titleProgress, [0, 1], [60, 0]);+ const titleOpacity = interpolate(titleProgress, [0, 1], [0, 1]);++ // Icons pop in staggered, after the title+ const iconBaseFrame = Math.round(fps * 0.5);++ const iconSize = Math.round(width * 0.085);++ return (+ <AbsoluteFill+ style={{+ backgroundColor: bg,+ fontFamily: FONT,+ justifyContent: "center",+ alignItems: "center",+ padding: width * 0.08,+ }}+ >+ {/* Accent bar */}+ <div+ style={{+ width: interpolate(titleProgress, [0, 1], [0, width * 0.18]),+ height: 10,+ backgroundColor: accent,+ borderRadius: 5,+ marginBottom: height * 0.04,+ }}+ />++ {/* Title / CTA */}+ <div+ style={{+ transform: `translateY(${titleY}px)`,+ opacity: titleOpacity,+ color: "#FFFFFF",+ fontSize: mode === "outro" ? width * 0.12 : width * 0.095,+ fontWeight: 700,+ lineHeight: 1.05,+ textAlign: "center",+ letterSpacing: -1,+ textTransform: mode === "outro" ? "none" : "none",+ }}+ >+ {title}+ </div>++ {handle && (+ <div+ style={{+ opacity: titleOpacity,+ color: accent,+ fontSize: width * 0.06,+ fontWeight: 700,+ marginTop: height * 0.02,+ }}+ >+ {handle}+ </div>+ )}++ {/* Social icons (outro emphasises them; intro shows them small if present) */}+ {platforms.length > 0 && (+ <div+ style={{+ display: "flex",+ gap: width * 0.05,+ marginTop: height * 0.05,+ alignItems: "center",+ justifyContent: "center",+ flexWrap: "wrap",+ }}+ >+ {platforms.map((p, i) => {+ const f = frame - (iconBaseFrame + i * Math.round(fps * 0.12));+ const pop = spring({ frame: Math.max(0, f), fps, config: { damping: 12, mass: 0.6 }, durationInFrames: Math.round(fps * 0.5) });+ const scale = interpolate(pop, [0, 1], [0.2, 1]);+ const op = interpolate(pop, [0, 1], [0, 1]);+ return (+ <div+ key={p}+ style={{+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: 8,+ transform: `scale(${scale})`,+ opacity: op,+ }}+ >+ <div+ style={{+ width: iconSize * 1.6,+ height: iconSize * 1.6,+ borderRadius: iconSize * 0.4,+ backgroundColor: "rgba(255,255,255,0.08)",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ }}+ >+ <Glyph name={p} size={iconSize} color="#FFFFFF" />+ </div>+ <div style={{ color: "rgba(255,255,255,0.7)", fontSize: width * 0.028, fontWeight: 700 }}>+ {PLATFORM_LABEL[p] || p}+ </div>+ </div>+ );+ })}+ </div>+ )}+ </AbsoluteFill>+ );+};diff --git a/remotion/src/Root.tsx b/remotion/src/Root.tsxindex 5ed5c53..5a92408 100644--- a/remotion/src/Root.tsx+++ b/remotion/src/Root.tsx@@ -3,6 +3,7 @@ import "@fontsource/dm-sans/700.css";import React from "react";import { Composition, getInputProps } from "remotion";import { CaptionedClip } from "./CaptionedClip";+import { Bookend } from "./Bookend";import { STYLES } from "./types";import type { Word } from "./types";@@ -14,6 +15,13 @@ const inputProps = getInputProps() as {faceY?: number | null;durationInFrames?: number;fps?: number;+ // Bookend props+ bookendMode?: "intro" | "outro";+ bookendTitle?: string;+ bookendHandle?: string;+ bookendPlatforms?: string[];+ bookendBg?: string;+ bookendAccent?: string;};export const RemotionRoot: React.FC = () => {@@ -37,6 +45,22 @@ export const RemotionRoot: React.FC = () => {faceY: inputProps.faceY ?? null,}}/>+ <Composition+ id="Bookend"+ component={Bookend}+ durationInFrames={durationInFrames}+ fps={fps}+ width={1080}+ height={1920}+ defaultProps={{+ mode: inputProps.bookendMode || "outro",+ title: inputProps.bookendTitle || "Follow for more",+ handle: inputProps.bookendHandle,+ platforms: inputProps.bookendPlatforms || ["tiktok", "instagram", "youtube", "x"],+ bg: inputProps.bookendBg || "#0B0B0F",+ accent: inputProps.bookendAccent || "#FFE000",+ }}+ /></>);};diff --git a/scripts/clip_studio.py b/scripts/clip_studio.pynew file mode 100644index 0000000..cac3eb2--- /dev/null+++ b/scripts/clip_studio.py@@ -0,0 +1,302 @@+#!/usr/bin/env python3+"""+clip_studio — cut a precise fragment from a video and wrap it with a Remotion+intro + "Follow for more" outro (with social icons).++Cut a fragment by TIMESTAMP or by PARAGRAPH text (matched against the+transcript). The fragment is rendered through podcli's existing face-crop ++caption pipeline, then an intro card and an outro card are stitched on:++ [ intro ] → [ captioned fragment ] → [ outro: Follow for more + icons ]++Usage:+ # by timestamp+ python scripts/clip_studio.py VIDEO --start 12 --end 38 --caption-style hormozi++ # by paragraph (finds the matching span in the transcript)+ python scripts/clip_studio.py VIDEO --paragraph "the part where they talk about X"++ # tune the bookends+ python scripts/clip_studio.py VIDEO --start 0 --end 30 \+ --intro-title "BIG IDEA" --outro-title "Follow for more" \+ --handle "@yourbrand" --platforms tiktok,instagram,youtube,x \+ --no-intro # skip the intro+"""+import argparse+import json+import os+import subprocess+import sys++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+# Capture the caller's CWD before we chdir into backend/ so relative video+# paths on the command line still resolve correctly.+_INVOKE_CWD = os.getcwd()+sys.path.insert(0, os.path.join(ROOT, "backend"))+os.chdir(os.path.join(ROOT, "backend"))++FFMPEG = os.environ.get("PODCLI_FFMPEG", "ffmpeg")+NODE = os.environ.get("PODCLI_NODE", "node")++# Brand config: remembered handle / platforms / colors / outro title so they+# don't have to be retyped each run. CLI flags override these; these override+# the built-in defaults below.+# Note: .env may set PODCLI_HOME to an empty string, so treat empty as unset.+_PODCLI_HOME = os.environ.get("PODCLI_HOME") or os.path.join(ROOT, ".podcli")+BRAND_PATH = os.path.join(_PODCLI_HOME, "brand.json")+BRAND_DEFAULTS = {+ "handle": None,+ "platforms": "tiktok,instagram,youtube,x",+ "outro_title": "Follow for more",+ "accent": "#FFE000",+ "bg": "#0B0B0F",+}+++def _load_brand() -> dict:+ try:+ with open(BRAND_PATH) as f:+ return json.load(f)+ except (FileNotFoundError, json.JSONDecodeError):+ return {}+++def _save_brand(data: dict):+ os.makedirs(os.path.dirname(BRAND_PATH), exist_ok=True)+ with open(BRAND_PATH, "w") as f:+ json.dump(data, f, indent=2)+++def _probe_duration(path: str) -> float:+ out = subprocess.run(+ ["ffprobe", "-v", "error", "-show_entries", "format=duration",+ "-of", "default=nw=1:nk=1", path],+ capture_output=True, text=True,+ )+ try:+ return float(out.stdout.strip())+ except ValueError:+ return 0.0+++def _transcribe(video: str, language: str | None):+ """Transcribe (cached) and return the word list."""+ from services.transcription import transcribe_file+ print(" [transcribe] running Whisper...", flush=True)+ res = transcribe_file(+ file_path=video, model_size="base", language=language,+ enable_diarization=False,+ progress_callback=lambda p, m: print(f" {p}% {m}", flush=True),+ )+ return res.get("words", [])+++def _find_paragraph(words: list, phrase: str) -> tuple[float, float]:+ """Find the time span of a paragraph by fuzzy-matching its text against+ the transcript word stream. Returns (start, end) seconds."""+ needle = "".join(c.lower() for c in phrase if c.isalnum() or c == " ").split()+ if not needle:+ raise SystemExit("Empty --paragraph text")+ hay = [("".join(c.lower() for c in w["word"] if c.isalnum())) for w in words]++ best_i, best_score = -1, 0+ win = len(needle)+ for i in range(0, max(1, len(hay) - win + 1)):+ window = hay[i:i + win]+ score = sum(1 for a, b in zip(window, needle) if a and (a == b or a.startswith(b) or b.startswith(a)))+ if score > best_score:+ best_score, best_i = score, i+ if best_i < 0 or best_score < max(1, win // 3):+ raise SystemExit(f"Could not confidently locate paragraph in transcript (best match {best_score}/{win} words).")+ start = float(words[best_i]["start"])+ end = float(words[min(best_i + win - 1, len(words) - 1)]["end"])+ print(f" [paragraph] matched {best_score}/{win} words → {start:.1f}s–{end:.1f}s", flush=True)+ return start, end+++def _render_fragment(video, start, end, words, style, crop, title, out_dir):+ """Render the fragment with face-crop + captions via the existing engine."""+ from services.clip_generator import generate_clip+ print(f" [fragment] rendering {start:.1f}s–{end:.1f}s ({style}, crop={crop})", flush=True)+ res = generate_clip(+ video_path=video, start_second=start, end_second=end,+ caption_style=style, crop_strategy=crop,+ transcript_words=words, title=title, output_dir=out_dir,+ clean_fillers=True, allow_ass_fallback=True,+ progress_callback=lambda p, m: print(f" {p}% {m}", flush=True),+ )+ return res["output_path"]+++def _render_bookend(mode, title, handle, platforms, seconds, out_path, accent, bg):+ cmd = [+ NODE, os.path.join(ROOT, "remotion", "render-bookend.mjs"),+ "--mode", mode, "--title", title,+ "--platforms", ",".join(platforms),+ "--seconds", str(seconds), "--output", out_path,+ "--accent", accent, "--bg", bg,+ ]+ if handle:+ cmd += ["--handle", handle]+ print(f" [{mode}] rendering bookend...", flush=True)+ r = subprocess.run(cmd, capture_output=True, text=True)+ if r.returncode != 0 or not os.path.exists(out_path):+ raise SystemExit(f"Bookend ({mode}) render failed:\n{r.stderr[-800:]}")+ return out_path+++def _concat(parts: list[str], out_path: str, fps: int = 30):+ """Concatenate parts (intro + clip + outro) in a single ffmpeg pass.++ Every part is normalized to 1080x1920 @ fps with stereo 44.1k audio inside+ the filtergraph, then joined with the concat filter. This gives an exact+ summed duration (no crossfade-offset drift) and a single clean re-encode.+ """+ n = len(parts)+ inputs = []+ for p in parts:+ inputs += ["-i", p]++ fc = []+ labels = []+ for i in range(n):+ # Normalize video: scale to fit 1080x1920, pad, set fps + SAR + format.+ fc.append(+ f"[{i}:v]scale=1080:1920:force_original_aspect_ratio=decrease,"+ f"pad=1080:1920:(ow-iw)/2:(oh-ih)/2:black,setsar=1,fps={fps},format=yuv420p[v{i}];"+ )+ # Normalize audio to a common format so concat doesn't choke.+ fc.append(+ f"[{i}:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo[a{i}];"+ )+ labels.append(f"[v{i}][a{i}]")+ fc.append("".join(labels) + f"concat=n={n}:v=1:a=1[v][a]")+ filtergraph = "".join(fc)++ cmd = [+ FFMPEG, "-y", *inputs,+ "-filter_complex", filtergraph,+ "-map", "[v]", "-map", "[a]",+ "-c:v", "libx264", "-crf", os.environ.get("PODCLI_CONCAT_CRF", "18"),+ "-preset", "medium", "-pix_fmt", "yuv420p",+ "-c:a", "aac", "-b:a", "192k", "-ar", "44100",+ "-movflags", "+faststart",+ out_path,+ ]+ r = subprocess.run(cmd, capture_output=True, text=True)+ if r.returncode != 0 or not os.path.exists(out_path):+ raise SystemExit(f"Concat failed:\n{r.stderr[-1000:]}")+ return out_path+++def main():+ ap = argparse.ArgumentParser(description="Cut a fragment + add intro/outro bookends.")+ ap.add_argument("video")+ ap.add_argument("--start", type=float, help="Fragment start (seconds)")+ ap.add_argument("--end", type=float, help="Fragment end (seconds)")+ ap.add_argument("--paragraph", help="Find fragment by matching this text in the transcript")+ ap.add_argument("--language", default=None, help="Transcription language (e.g. es). Auto-detect if omitted.")+ ap.add_argument("--caption-style", default="hormozi", choices=["hormozi", "karaoke", "subtle", "branded"])+ ap.add_argument("--crop", default="face", choices=["center", "face", "speaker", "speaker-hardcut"])+ ap.add_argument("--output", default=None, help="Final output path")+ # bookends (defaults are None so we can tell what the user explicitly set;+ # unset values fall back to the saved brand config, then BRAND_DEFAULTS)+ ap.add_argument("--intro-title", default=None, help="Intro headline (default: derived from first words)")+ ap.add_argument("--outro-title", default=None, help="Outro call-to-action (brand default: 'Follow for more')")+ ap.add_argument("--handle", default=None, help="Handle shown on cards, e.g. @yourbrand")+ ap.add_argument("--platforms", default=None, help="Comma-separated: tiktok,instagram,youtube,x")+ ap.add_argument("--intro-seconds", type=float, default=2.0)+ ap.add_argument("--outro-seconds", type=float, default=3.0)+ ap.add_argument("--accent", default=None, help="Accent color hex (brand default: #FFE000)")+ ap.add_argument("--bg", default=None, help="Background color hex (brand default: #0B0B0F)")+ ap.add_argument("--no-intro", action="store_true")+ ap.add_argument("--no-outro", action="store_true")+ ap.add_argument("--save-brand", action="store_true",+ help="Save the given handle/platforms/outro-title/accent/bg as the default brand and exit")+ args = ap.parse_args()++ # Resolve brand fields: CLI flag > saved brand.json > BRAND_DEFAULTS+ brand = {**BRAND_DEFAULTS, **_load_brand()}+ handle = args.handle if args.handle is not None else brand["handle"]+ platforms_str = args.platforms if args.platforms is not None else brand["platforms"]+ outro_title = args.outro_title if args.outro_title is not None else brand["outro_title"]+ accent = args.accent if args.accent is not None else brand["accent"]+ bg = args.bg if args.bg is not None else brand["bg"]++ if args.save_brand:+ saved = {"handle": handle, "platforms": platforms_str,+ "outro_title": outro_title, "accent": accent, "bg": bg}+ _save_brand(saved)+ print(f" ✓ Brand saved to {BRAND_PATH}")+ for k, v in saved.items():+ print(f" {k}: {v}")+ return++ video = args.video if os.path.isabs(args.video) else os.path.join(_INVOKE_CWD, args.video)+ video = os.path.abspath(video)+ if not os.path.exists(video):+ raise SystemExit(f"Video not found: {video}")+ out_dir = os.path.join(ROOT, "data", "output")+ os.makedirs(out_dir, exist_ok=True)++ # Need a transcript if cutting by paragraph or if rendering captions.+ words = _transcribe(video, args.language)++ if args.paragraph:+ start, end = _find_paragraph(words, args.paragraph)+ elif args.start is not None and args.end is not None:+ start, end = args.start, args.end+ else:+ raise SystemExit("Provide either --start/--end or --paragraph")++ # 1. Fragment+ fragment = _render_fragment(+ video, start, end, words, args.caption_style, args.crop, "fragment", out_dir,+ )++ platforms = [p.strip() for p in platforms_str.split(",") if p.strip()]+ parts = []++ # 2. Intro (optional)+ if not args.no_intro:+ intro_title = args.intro_title+ if not intro_title:+ # derive a short headline from the first ~4 words of the fragment+ frag_words = [w["word"] for w in words if start <= w["start"] < end][:4]+ intro_title = " ".join(frag_words) or "Watch this"+ intro = _render_bookend(+ "intro", intro_title, handle, platforms,+ args.intro_seconds, os.path.join(out_dir, "_intro.mp4"), accent, bg,+ )+ parts.append(intro)++ parts.append(fragment)++ # 3. Outro (optional)+ if not args.no_outro:+ outro = _render_bookend(+ "outro", outro_title, handle, platforms,+ args.outro_seconds, os.path.join(out_dir, "_outro.mp4"), accent, bg,+ )+ parts.append(outro)++ # 4. Stitch+ if args.output:+ final = args.output if os.path.isabs(args.output) else os.path.join(_INVOKE_CWD, args.output)+ else:+ final = os.path.join(out_dir, "studio_final.mp4")+ if len(parts) == 1:+ # no bookends — fragment is the result+ import shutil+ shutil.copy(parts[0], final)+ else:+ _concat(parts, final)++ dur = _probe_duration(final)+ print(f"\n ✓ DONE {final}")+ print(f" duration={dur:.1f}s (intro {'on' if not args.no_intro else 'off'}, "+ f"outro {'on' if not args.no_outro else 'off'})")+++if __name__ == "__main__":+ main()