diff --git a/backend/cli.py b/backend/cli.py index 5ff373b..b66dcc5 100644 --- a/backend/cli.py +++ b/backend/cli.py @@ -76,6 +76,7 @@ def _reveal_in_os(path: str) -> None: from config.paths import paths from config.server import DEFAULT_PORT, resolve_web_server_port, web_server_url +from services.formats import FORMATS from presets import DEFAULT_PRESET, MIN_CLIP_DURATION, MAX_CLIP_DURATION, TARGET_CLIP_DURATION_MIN, TARGET_CLIP_DURATION_MAX from services.knowledge_base import is_empty as kb_is_empty, kb_files @@ -5319,7 +5320,7 @@ def main(): "speaker framing work on a transcript that carries no speaker labels.") proc.add_argument("--crop-keyframes", dest="crop_keyframes", default=None, help="Hand-placed crop positions, as JSON. Used by --crop manual.") - proc.add_argument("--format", choices=["vertical", "horizontal", "square"], help="Output aspect ratio (default: vertical)") + proc.add_argument("--format", choices=list(FORMATS), help="Output aspect ratio (default: vertical). topic is a 5-15 minute 16:9 segment") proc.add_argument("--profile", choices=["podcast", "party", "action"], help="Detection profile: podcast (transcript-first, default), party/action (laughter/energy highlights)") proc.add_argument("--logo", help="Logo image (asset name or path)") proc.add_argument("--logo-position", choices=["top-left", "top-center", "top-right", "bottom-left", "bottom-center", "bottom-right"], @@ -5491,7 +5492,7 @@ def main(): "speaker framing work on a transcript that carries no speaker labels.") studio.add_argument("--crop-keyframes", dest="crop_keyframes", default=None, help="Hand-placed crop positions, as JSON. Used by --crop manual.") - studio.add_argument("--format", choices=["vertical", "horizontal", "square"], default="vertical", + studio.add_argument("--format", choices=list(FORMATS), default="vertical", help="Output aspect ratio (default: vertical)") studio.add_argument("--template", help="Cut in a saved look (podcli Pro). Name or id.") studio.add_argument("--logo", help="Logo image (asset name or path)") diff --git a/backend/clip_studio.py b/backend/clip_studio.py index b1a0b89..0d9761f 100644 --- a/backend/clip_studio.py +++ b/backend/clip_studio.py @@ -281,7 +281,7 @@ def _render_fragment(video, start, end, words, style, crop, title, out_dir, fmt= logo_path=logo, name_card=name_card, motion=motion, topic=topic, progress=progress, cards=cards, brand=brand, theme=theme, font_family=font_family, captions=captions, hook=hook, - clean_fillers=True, allow_ass_fallback=True, + allow_ass_fallback=True, progress_callback=lambda p, m: print(f" {p}% {m}", flush=True), ) return res["output_path"] @@ -360,6 +360,8 @@ def _concat(parts: list[str], out_path: str, fps: int = 30, def main(): + from services.formats import FORMATS + 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)") @@ -372,7 +374,7 @@ def main(): ap.add_argument("--caption-position", default="auto", choices=["auto", "upper", "center", "lower"]) ap.add_argument("--caption-scale", type=float, default=1.0) ap.add_argument("--crop", default="face", choices=["center", "face", "speaker", "speaker-hardcut"]) - ap.add_argument("--format", default="vertical", choices=["vertical", "horizontal", "square"], + ap.add_argument("--format", default="vertical", choices=list(FORMATS), help="Output aspect ratio (default: vertical)") ap.add_argument("--output", default=None, help="Final output path") ap.add_argument("--logo", default=None, help="Logo image (asset name or path)") diff --git a/backend/main.py b/backend/main.py index 931616c..588959b 100644 --- a/backend/main.py +++ b/backend/main.py @@ -226,7 +226,7 @@ def handle_create_clip(task_id: str, params: dict): name_card=params.get("name_card"), motion=params.get("motion"), bookend_fade=params.get("bookend_fade", 0.0), - clean_fillers=params.get("clean_fillers", True), + clean_fillers=params.get("clean_fillers"), face_map=params.get("face_map"), keep_segments=params.get("keep_segments"), hook=params.get("hook"), @@ -294,7 +294,7 @@ def render_one(i: int, clip: dict) -> dict: name_card=clip.get("name_card") or params.get("name_card"), motion=clip.get("motion") or params.get("motion"), bookend_fade=params.get("bookend_fade", 0.0), - clean_fillers=params.get("clean_fillers", True), + clean_fillers=params.get("clean_fillers"), face_map=params.get("face_map"), keep_segments=clip.get("keep_segments"), hook=clip.get("hook"), diff --git a/backend/services/audio_normalize.py b/backend/services/audio_normalize.py index 7b10750..f4e1c45 100644 --- a/backend/services/audio_normalize.py +++ b/backend/services/audio_normalize.py @@ -9,7 +9,7 @@ import json -from services.media_probe import FFMPEG_TIMEOUT +from services.media_probe import ffmpeg_timeout, get_media_duration_seconds from utils.proc import run as proc_run @@ -25,6 +25,8 @@ def normalize_audio( Falls back to a single-pass loudnorm when measurement is missing or returns −inf (silent / very short clips). """ + timeout = ffmpeg_timeout(get_media_duration_seconds(input_path)) + # First pass: measure current loudness. measure_cmd = [ "ffmpeg", "-y", @@ -32,7 +34,7 @@ def normalize_audio( "-af", f"loudnorm=I={target_lufs}:TP=-1.5:LRA=11:print_format=json", "-f", "null", "-", ] - result = proc_run(measure_cmd, timeout=FFMPEG_TIMEOUT, check=False) + result = proc_run(measure_cmd, timeout=timeout, check=False) loudnorm_data = _parse_loudnorm_stats(result.stderr) @@ -62,7 +64,7 @@ def normalize_audio( "-movflags", "+faststart", output_path, ] - result = proc_run(cmd, timeout=FFMPEG_TIMEOUT, check=False) + result = proc_run(cmd, timeout=timeout, check=False) if result.returncode != 0: raise RuntimeError(f"FFmpeg normalize failed: {result.stderr[-500:]}") return output_path diff --git a/backend/services/clip_generator.py b/backend/services/clip_generator.py index fcff911..9ff83d2 100644 --- a/backend/services/clip_generator.py +++ b/backend/services/clip_generator.py @@ -43,7 +43,7 @@ ) from config.caption_styles import get_style from services.formats import get_format -from services.media_probe import align_av_duration, ffmpeg_timeout +from services.media_probe import align_av_duration, ffmpeg_timeout, remotion_timeout _FILLER_WORDS = frozenset([ "um", "uh", "uhh", "uhm", "umm", "hmm", "hm", "mhm", @@ -735,6 +735,7 @@ def _render_with_remotion( font_family: Optional[str] = None, theme: Optional[dict] = None, captions: bool = True, + duration: Optional[float] = None, ) -> tuple[bool, Optional[str]]: """ Render captions using Remotion. Returns (success, optional_prores_overlay_path). @@ -916,7 +917,7 @@ def _render_with_remotion( # for months and the reason went to /dev/null with the rest of it. result = _run_streaming( cmd, - timeout=2 * 50 * 60 + 300, + timeout=remotion_timeout(duration), cwd=project_root, env=remotion_env, ) @@ -974,7 +975,7 @@ def generate_clip( name_card: Optional[dict] = None, motion: Optional[dict] = None, bookend_fade: float = 0.0, - clean_fillers: bool = True, + clean_fillers: Optional[bool] = None, keep_segments: list[dict] = None, hook: Optional[dict] = None, trim_opening: Optional[bool] = None, @@ -1060,6 +1061,9 @@ def generate_clip( spec = get_format(format) + tighten_body = spec.auto_tighten if clean_fillers is None else clean_fillers + clean_caption_words = clean_fillers is not False + # An episode that was never filmed takes the other road entirely. Branching # here rather than at the five call sites means every caller of this # function gets it, and none of them has to know the difference: what comes @@ -1140,7 +1144,7 @@ def generate_clip( # If Claude returned a single segment, still auto-trim pauses within it. # Multiple segments means Claude made deliberate editorial cuts. Trust those. - if len(keep_segments) == 1 and transcript_words and clean_fillers: + if len(keep_segments) == 1 and transcript_words and tighten_body: auto_segments = _build_tight_segments( transcript_words, start_second, end_second, ) @@ -1160,7 +1164,7 @@ def generate_clip( end_second, _ = _bound_range_to_source(start_second, end_second, None, source_duration) # Auto-build tight segments: cut long pauses and isolated fillers - if transcript_words and clean_fillers: + if transcript_words and tighten_body: auto_segments = _build_tight_segments( transcript_words, start_second, end_second, ) @@ -1371,7 +1375,7 @@ def generate_clip( words_in_range = len(clip_words) # Clean filler words - if clean_fillers: + if clean_caption_words: clip_words = _clean_transcript_words(clip_words) if not clip_words: @@ -1425,6 +1429,7 @@ def generate_clip( font_family=font_family, theme=theme, captions=captions, + duration=duration, ) if not remotion_ok and not captions: diff --git a/backend/services/formats.py b/backend/services/formats.py index 91cfc66..f329b22 100644 --- a/backend/services/formats.py +++ b/backend/services/formats.py @@ -27,6 +27,7 @@ class FormatSpec: editor: str pacing: str lens: str + auto_tighten: bool = True @property def dims(self) -> tuple[int, int]: @@ -74,6 +75,23 @@ def ratio(self) -> float: pacing="SHORTER IS BETTER. A punchy 25s clip outperforms a 40s clip every time.", lens="think like a social editor", ), + "topic": FormatSpec( + name="topic", + width=1920, height=1080, + reframe=False, + caption_profile="lower_third", + dur_min=300, dur_max=900, + target_min=420, target_max=720, + editor="an editor cutting a full standalone topic segment out of a long-form show", + pacing=( + "The segment needs a clear setup, a developed middle, and a payoff " + "that closes the topic. Open where the topic is introduced and end " + "where it is resolved. Cut tangents, but keep the back and forth " + "that builds toward the point." + ), + lens="think like a long-form editor building a chapter", + auto_tighten=False, + ), } DEFAULT_FORMAT = "vertical" diff --git a/backend/services/media_probe.py b/backend/services/media_probe.py index 6d2948a..e728e90 100644 --- a/backend/services/media_probe.py +++ b/backend/services/media_probe.py @@ -56,10 +56,37 @@ def ffmpeg_timeout(duration_s: float | None = None) -> float: """Seconds allowed for one encode. Probes keep using FFMPEG_TIMEOUT.""" base = float(FFMPEG_TIMEOUT) if duration_s and duration_s > 0: - return min(1800.0, max(base, duration_s * 20.0 + 120.0)) + ceiling = max(1800.0, min(7200.0, duration_s * 4.0)) + return min(ceiling, max(base, duration_s * 20.0 + 120.0)) return base +REMOTION_TIMEOUT = 2 * 50 * 60 + 300 + + +def remotion_timeout(duration_s: float | None = None) -> float: + base = float(REMOTION_TIMEOUT) + if duration_s and duration_s > 0: + return max(base, duration_s * 12.0 + 900.0) + return base + + +def _encode_duration(cmd_parts: list) -> float | None: + for i, part in enumerate(cmd_parts[:-1]): + if part == "-t": + try: + seconds = float(cmd_parts[i + 1]) + except (TypeError, ValueError): + break + if seconds > 0: + return seconds + for i, part in enumerate(cmd_parts[:-1]): + if part == "-i": + seconds = get_media_duration_seconds(str(cmd_parts[i + 1])) + return seconds if seconds > 0 else None + return None + + def run_ffmpeg_with_fallback( cmd_parts_before_enc: list, cmd_parts_after_enc: list, @@ -78,6 +105,8 @@ def run_ffmpeg_with_fallback( enc_flags = get_video_encode_flags() fallback_flags = cpu_flags() cmd = cmd_parts_before_enc + enc_flags + cmd_parts_after_enc + [output_path] + if duration_s is None: + duration_s = _encode_duration(cmd_parts_before_enc) timeout = ffmpeg_timeout(duration_s) result = proc_run(cmd, timeout=timeout, check=False) diff --git a/backend/services/reel.py b/backend/services/reel.py index f59dcd8..6ab98a9 100644 --- a/backend/services/reel.py +++ b/backend/services/reel.py @@ -16,6 +16,7 @@ from utils.proc import run as proc_run from config.paths import paths from services.formats import get_format +from services.media_probe import ffmpeg_timeout def _sessions_dir() -> str: @@ -228,7 +229,7 @@ def _cut(source: str, out_dir: str, idx: int, m: Moment, format: str, logo: str else: cmd += ["-vf", _scale_filter(format)] cmd += [*_encode_flags(), out, "-loglevel", "error"] - proc_run(cmd, timeout=300, check=True) + proc_run(cmd, timeout=ffmpeg_timeout(m.duration), check=True) return out @@ -248,17 +249,19 @@ def build_reel(session: ReelSession, progress_callback: Optional[Callable] = Non session.save() reel = os.path.join(session.out_dir, "highlights_reel.mp4") + reel_seconds = sum(m.duration for _, m in active) lst = os.path.join(session.out_dir, "_concat.txt") with open(lst, "w", encoding="utf-8") as f: for x in files: p = os.path.abspath(x).replace("\\", "/").replace("'", "'\\''") f.write(f"file '{p}'\n") r = proc_run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", lst, - "-c", "copy", reel, "-loglevel", "error"], timeout=300, check=False) + "-c", "copy", reel, "-loglevel", "error"], + timeout=ffmpeg_timeout(reel_seconds), check=False) if r.returncode != 0: proc_run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", lst, *_encode_flags(), reel, "-loglevel", "error"], - timeout=900, check=True) + timeout=max(900.0, ffmpeg_timeout(reel_seconds)), check=True) if progress_callback: progress_callback(100, f"built reel with {len(files)} moments") return reel diff --git a/backend/services/video_cut.py b/backend/services/video_cut.py index db8024a..9c84030 100644 --- a/backend/services/video_cut.py +++ b/backend/services/video_cut.py @@ -9,7 +9,7 @@ import os -from services.media_probe import FFMPEG_TIMEOUT +from services.media_probe import FFMPEG_TIMEOUT, ffmpeg_timeout, get_media_duration_seconds from utils.proc import run as proc_run @@ -43,7 +43,7 @@ def cut_segment( "-avoid_negative_ts", "make_zero", output_path, ] - result = proc_run(cmd, timeout=FFMPEG_TIMEOUT, check=False) + result = proc_run(cmd, timeout=ffmpeg_timeout(duration), check=False) if result.returncode != 0: raise RuntimeError(f"FFmpeg cut failed: {result.stderr[-500:]}") return output_path @@ -113,7 +113,7 @@ def cut_multi_segment( "-movflags", "+faststart", output_path, ] - result = proc_run(cmd, timeout=FFMPEG_TIMEOUT, check=False) + result = proc_run(cmd, timeout=ffmpeg_timeout(sum(part_durations)), check=False) if result.returncode != 0: raise RuntimeError(f"FFmpeg concat failed: {result.stderr[-500:]}") @@ -159,7 +159,7 @@ def verify_full_decode(path: str, max_error_lines: int = 3) -> str | None: as a real decode failure once more than a few such lines show up. """ cmd = ["ffmpeg", "-v", "error", "-threads", "auto", "-i", path, "-f", "null", "-"] - result = proc_run(cmd, timeout=FFMPEG_TIMEOUT, check=False) + result = proc_run(cmd, timeout=ffmpeg_timeout(get_media_duration_seconds(path)), check=False) stderr = (result.stderr or "").strip() if result.returncode != 0: return stderr[-1000:] if stderr else f"ffmpeg exited {result.returncode} decoding the output" diff --git a/remotion/render.mjs b/remotion/render.mjs index a371df7..a5697fd 100644 --- a/remotion/render.mjs +++ b/remotion/render.mjs @@ -80,6 +80,9 @@ const timeoutFor = (durationSec) => { return Math.round(Math.min(50 * 60_000, Math.max(120_000, 90_000 + durationSec * 15_000))); }; +const compositeTimeoutFor = (durationSec) => + Math.round(Math.min(60 * 60_000, Math.max(300_000, 120_000 + durationSec * 20_000))); + const videoCacheBytes = () => { const mb = parseInt(process.env.PODCLI_REMOTION_VIDEO_CACHE_MB ?? "", 10); @@ -425,7 +428,7 @@ async function main() { "-map", "0:a", "-c:a", "copy", path.resolve(opts.output), ], - { stdio: ["pipe", "pipe", "pipe"], timeout: 300000, encoding: "utf8" } + { stdio: ["pipe", "pipe", "pipe"], timeout: compositeTimeoutFor(durationSec), encoding: "utf8" } ); if (composite.error || composite.status !== 0) { diff --git a/src/handlers/batch-clips.handler.ts b/src/handlers/batch-clips.handler.ts index f162ae1..ba57cac 100644 --- a/src/handlers/batch-clips.handler.ts +++ b/src/handlers/batch-clips.handler.ts @@ -6,10 +6,12 @@ import { ClipsHistory } from "../services/clips-history.js"; import { paths } from "../config/paths.js"; import { webServerUrl } from "../config/server.js"; import { validateClipRange } from "../utils/clip-validation.js"; +import { resolveCleanFillers } from "../utils/clean-fillers.js"; import { findContentType } from "../utils/transcript.js"; import { validateHook } from "../utils/clip-hook.js"; import { transcriptVideoMismatch } from "../utils/video-identity.js"; import { childLogger } from "../utils/logger.js"; +import { FORMATS } from "../models/index.js"; import type { BatchClipsInput, BatchClipSpec, @@ -85,7 +87,7 @@ export const batchClipsToolDef = { }, format: { type: "string", - enum: ["vertical", "horizontal", "square"], + enum: [...FORMATS], }, allow_ass_fallback: { type: "boolean", @@ -185,7 +187,7 @@ export async function handleBatchClips(input: BatchClipsInput): Promise const deselected = state?.deselectedIndices ?? []; const batchFormat = input.format || settings.format || "vertical"; - const cleanFillers = input.clean_fillers ?? settings.cleanFillers ?? true; + const cleanFillers = resolveCleanFillers(input.clean_fillers, settings.cleanFillers, batchFormat); const buildClipFromSuggestion = (s: SuggestedClip, num: number): BatchClipSpec => ({ start_second: s.start_second, diff --git a/src/handlers/create-clip.handler.ts b/src/handlers/create-clip.handler.ts index 0b13a2a..f37f593 100644 --- a/src/handlers/create-clip.handler.ts +++ b/src/handlers/create-clip.handler.ts @@ -2,10 +2,12 @@ import { PythonExecutor } from "../services/python-executor.js"; import { FileManager } from "../services/file-manager.js"; import { readUIStateFile } from "../services/ui-state-file.js"; import { paths } from "../config/paths.js"; +import { FORMATS } from "../models/index.js"; import type { ClipResult, CreateClipInput, SuggestedClip, UIState } from "../models/index.js"; import { childLogger } from "../utils/logger.js"; import { sliceTranscript } from "../utils/transcript.js"; import { validateClipRange } from "../utils/clip-validation.js"; +import { resolveCleanFillers } from "../utils/clean-fillers.js"; import { validateHook } from "../utils/clip-hook.js"; import { transcriptVideoMismatch } from "../utils/video-identity.js"; @@ -72,9 +74,9 @@ export const createClipToolDef = { }, format: { type: "string", - enum: ["vertical", "horizontal", "square"], + enum: [...FORMATS], description: - "Output aspect ratio. vertical=9:16 shorts, horizontal=16:9, square=1:1. Auto-loaded from session settings if omitted. Default: vertical.", + "Output aspect ratio. vertical=9:16 shorts, horizontal=16:9 up to 5 minutes, square=1:1, topic=16:9 segments of 5-15 minutes. Auto-loaded from session settings if omitted. Default: vertical.", }, transcript_words: { type: "array", @@ -247,7 +249,7 @@ export async function handleCreateClip(input: CreateClipInput): Promise transcript_words: transcriptWords, title, output_dir: paths.output, - clean_fillers: input.clean_fillers ?? settings.cleanFillers ?? true, + clean_fillers: resolveCleanFillers(input.clean_fillers, settings.cleanFillers, format), allow_ass_fallback: input.allow_ass_fallback === true, keep_caption_overlay: input.keep_caption_overlay === true, write_clean_variant: input.write_clean_variant === true, diff --git a/src/models/index.ts b/src/models/index.ts index 70a03c7..1e30d22 100644 --- a/src/models/index.ts +++ b/src/models/index.ts @@ -92,7 +92,9 @@ export type CaptionStyle = "branded" | "hormozi" | "karaoke" | "subtle"; export type CropStrategy = "center" | "face" | "speaker"; -export type Format = "vertical" | "horizontal" | "square"; +export const FORMATS = ["vertical", "horizontal", "square", "topic"] as const; + +export type Format = (typeof FORMATS)[number]; export interface ClipRequest { video_path: string; diff --git a/src/server.ts b/src/server.ts index 3be4002..217b84a 100644 --- a/src/server.ts +++ b/src/server.ts @@ -47,6 +47,7 @@ import { childLogger } from "./utils/logger.js"; import { mcpError } from "./utils/errors.js"; import { transcriptVideoMismatch } from "./utils/video-identity.js"; import { podcliVersion, studioStartCommand } from "./version.js"; +import { FORMATS } from "./models/index.js"; import type { ClipHook, SuggestedClip, UIState } from "./models/index.js"; const log = childLogger("server"); @@ -194,7 +195,7 @@ const apiResponseSchema = z.looseObject({ }); const cropStrategySchema = z.enum(["center", "face", "speaker"]); -const formatSchema = z.enum(["vertical", "horizontal", "square"]); +const formatSchema = z.enum(FORMATS); function exportClipFromSuggestion( s: SuggestedClip, @@ -613,7 +614,7 @@ export function createServer(): McpServer { quality: z.enum(["low", "medium", "high", "max"]).optional(), caption_style: z.enum(["branded", "hormozi", "karaoke", "subtle"]).optional(), crop: z.enum(["center", "face", "speaker", "speaker-hardcut"]).optional(), - format: z.enum(["vertical", "horizontal", "square"]).optional(), + format: z.enum(FORMATS).optional(), language: z.string().optional(), engine: z.enum(["whisper-py", "whispercpp", "assemblyai", "omnilingual"]).optional(), fast: z.boolean().optional(), @@ -746,10 +747,12 @@ export function createServer(): McpServer { .default("speaker") .describe("Cropping strategy"), format: z - .enum(["vertical", "horizontal", "square"]) + .enum(FORMATS) .optional() .default("vertical") - .describe("Output aspect ratio (vertical=9:16, horizontal=16:9, square=1:1)"), + .describe( + "Output aspect ratio (vertical=9:16, horizontal=16:9 up to 5 minutes, square=1:1, topic=16:9 segments of 5-15 minutes)", + ), allow_ass_fallback: z .boolean() .optional() @@ -1092,7 +1095,7 @@ export function createServer(): McpServer { .enum(["hormozi", "karaoke", "subtle", "branded"]) .optional(), crop_strategy: z.enum(["center", "face", "speaker"]).optional(), - format: z.enum(["vertical", "horizontal", "square"]).optional(), + format: z.enum(FORMATS).optional(), allow_ass_fallback: z.boolean().optional(), keep_caption_overlay: z.boolean().optional(), write_clean_variant: z.boolean().optional(), @@ -1616,10 +1619,7 @@ export function createServer(): McpServer { .string() .optional() .describe("Crop strategy (for check)"), - format: z - .enum(["vertical", "horizontal", "square"]) - .optional() - .describe("Output format (for check)"), + format: z.enum(FORMATS).optional().describe("Output format (for check)"), limit: z.number().optional().default(20).describe("Max results for list"), }, async ({ diff --git a/src/services/python-executor.ts b/src/services/python-executor.ts index dd48d71..ec1e0e9 100644 --- a/src/services/python-executor.ts +++ b/src/services/python-executor.ts @@ -3,6 +3,7 @@ import { v4 as uuidv4 } from "uuid"; import { z } from "zod"; import { absentWhenNull } from "../utils/zod-helpers.js"; import { paths, pythonEnv } from "../config/paths.js"; +import { FORMATS } from "../models/index.js"; import type { TaskRequest, TaskResult, ProgressEvent } from "../models/index.js"; type ProgressCallback = (event: ProgressEvent) => void; @@ -111,7 +112,7 @@ const clipResultRowSchema = z.looseObject({ source_end_second: absentWhenNull(z.number()), caption_style: absentWhenNull(z.string()), crop_strategy: absentWhenNull(z.string()), - format: absentWhenNull(z.enum(["vertical", "horizontal", "square"])), + format: absentWhenNull(z.enum(FORMATS)), title: absentWhenNull(z.string()), file_size_mb: absentWhenNull(z.number()), duration: absentWhenNull(z.number()), diff --git a/src/topic-format.test.ts b/src/topic-format.test.ts new file mode 100644 index 0000000..d3e059d --- /dev/null +++ b/src/topic-format.test.ts @@ -0,0 +1,106 @@ +import { describe, it, expect, beforeAll, afterAll } from "vitest"; +import { mkdirSync, mkdtempSync, rmSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; +import { z } from "zod"; +import { connectClient } from "./test-support/mcp-client.js"; +import { FORMATS } from "./models/index.js"; +import { createClipToolDef } from "./handlers/create-clip.handler.js"; +import { batchClipsToolDef } from "./handlers/batch-clips.handler.js"; + +const tmp = mkdtempSync(join(tmpdir(), "podcli-topic-format-")); +const savedHome = process.env.PODCLI_HOME; +const savedData = process.env.PODCLI_DATA; +const savedPort = process.env.PODCLI_PORT; + +let createServer: typeof import("./server.js").createServer; + +beforeAll(async () => { + process.env.PODCLI_HOME = join(tmp, "home"); + process.env.PODCLI_DATA = join(tmp, "data"); + process.env.PODCLI_PORT = "18427"; + mkdirSync(process.env.PODCLI_HOME, { recursive: true }); + ({ createServer } = await import("./server.js")); +}); + +afterAll(() => { + if (savedHome === undefined) delete process.env.PODCLI_HOME; + else process.env.PODCLI_HOME = savedHome; + + if (savedData === undefined) delete process.env.PODCLI_DATA; + else process.env.PODCLI_DATA = savedData; + + if (savedPort === undefined) delete process.env.PODCLI_PORT; + else process.env.PODCLI_PORT = savedPort; + rmSync(tmp, { recursive: true, force: true }); +}); + +const formatOptions = z.looseObject({ enum: z.array(z.string()) }); + +const topLevelFormat = z.looseObject({ + properties: z.looseObject({ format: formatOptions.optional() }).optional(), +}); + +const batchClipFormat = z.looseObject({ + properties: z.looseObject({ + clips: z.looseObject({ + items: z.looseObject({ + properties: z.looseObject({ format: formatOptions }), + }), + }), + }), +}); + +describe("topic format wiring", () => { + it("lists topic after the existing formats", () => { + expect([...FORMATS]).toEqual(["vertical", "horizontal", "square", "topic"]); + }); + + it("offers topic in the create and batch tool definitions", () => { + expect(createClipToolDef.inputSchema.properties.format.enum).toEqual([...FORMATS]); + expect(batchClipsToolDef.inputSchema.properties.clips.items.properties.format.enum).toEqual([...FORMATS]); + }); + + it("offers topic on every registered tool that takes a clip format, except reels", async () => { + const client = await connectClient(createServer()); + + try { + const { tools } = await client.listTools(); + const clipFormats = new Map(); + + for (const tool of tools) { + const options = topLevelFormat.parse(tool.inputSchema).properties?.format?.enum; + + if (options?.includes("vertical")) clipFormats.set(tool.name, options); + } + + expect([...clipFormats.keys()].sort()).toEqual(["clip_history", "create_clip", "manage_reel", "process_episode"]); + + for (const [name, options] of clipFormats) { + if (name !== "manage_reel") expect(options, name).toContain("topic"); + } + + const batch = tools.find((tool) => tool.name === "batch_create_clips"); + + expect(batchClipFormat.parse(batch?.inputSchema).properties.clips.items.properties.format.enum).toContain("topic"); + } finally { + await client.close(); + } + }); + + it("accepts topic and rejects unknown formats at the create_clip schema", async () => { + const client = await connectClient(createServer()); + + try { + const accepted = await client.callTool({ name: "create_clip", arguments: { clip_number: 1, format: "topic" } }); + const rejected = await client.callTool({ name: "create_clip", arguments: { clip_number: 1, format: "tall" } }); + const replyText = z.looseObject({ content: z.array(z.looseObject({ text: z.string().optional() })) }); + const textOf = (reply: z.infer) => reply.content.map((block) => block.text ?? "").join("\n"); + + expect(textOf(replyText.parse(accepted))).not.toMatch(/Invalid arguments/); + expect(textOf(replyText.parse(rejected))).toMatch(/Invalid arguments/); + } finally { + await client.close(); + } + }); +}); diff --git a/src/ui/client/EpisodeWorkspace.jsx b/src/ui/client/EpisodeWorkspace.jsx index 85f3cf5..a9dde1b 100644 --- a/src/ui/client/EpisodeWorkspace.jsx +++ b/src/ui/client/EpisodeWorkspace.jsx @@ -49,6 +49,7 @@ const FORMAT_BOUNDS = { vertical: { min: 20, max: 45, ceiling: 60 }, square: { min: 20, max: 45, ceiling: 60 }, horizontal: { min: 60, max: 300, ceiling: 360 }, + topic: { min: 300, max: 900, ceiling: 960 }, }; const boundsFor = (f) => FORMAT_BOUNDS[f] || FORMAT_BOUNDS.vertical; @@ -1477,7 +1478,7 @@ const onKeyActivate = (fn) => (e) => { const onCaptionChange = (v) => { setCaptionStyle(v); flashSetting('caption'); }; const onCropChange = (v) => { setCropStrategy(v); flashSetting('crop'); }; - const onFormatChange = (v) => { setFormat(v); flashSetting('format'); }; + const onFormatChange = (v) => { setFormat(v); setCleanFillers(v !== 'topic'); flashSetting('format'); }; // Click clip row → seek source video const onClipClick = (idx) => { @@ -2567,7 +2568,7 @@ const onKeyActivate = (fn) => (e) => {
diff --git a/src/ui/web-server.ts b/src/ui/web-server.ts index 538d119..14d31ac 100644 --- a/src/ui/web-server.ts +++ b/src/ui/web-server.ts @@ -46,6 +46,7 @@ import { paths, pythonEnv } from "../config/paths.js"; import { webServerPort } from "../config/server.js"; import { writeFileAtomicSync } from "../utils/atomic-file.js"; import { maxClipSeconds, validateClipRange, validateSuggestionRange } from "../utils/clip-validation.js"; +import { resolveCleanFillers } from "../utils/clean-fillers.js"; import { playbackDuration, validateHook } from "../utils/clip-hook.js"; import { hookSchema } from "../handlers/suggest-clips.handler.js"; import { needsFrame, thumbnailRenderArgs } from "../utils/thumbnail-layout.js"; @@ -73,6 +74,7 @@ import { parseFullEpisodeProgress, } from "../utils/full-episode-export.js"; import { buildYtDlpArgs, isCookieBrowser, ytDlpHint } from "../utils/ytdlp-args.js"; +import { FORMATS } from "../models/index.js"; import type { BatchClipsResult, ClipHistoryEntry, @@ -87,6 +89,8 @@ import type { const log = childLogger("web-server"); +const FORMAT_NAMES: readonly string[] = FORMATS; + const stringValue = z.string(); const numberValue = z.number(); @@ -1464,7 +1468,7 @@ app.post("/api/create-clip", async (req, res) => { } const duration = end_second - start_second; - const maxDur = format === "horizontal" ? 300 : 180; + const maxDur = maxClipSeconds(format); if (duration > maxDur) { res.status(400).json({ @@ -1494,12 +1498,10 @@ app.post("/api/create-clip", async (req, res) => { return; } - const validFormats = ["vertical", "horizontal", "square"]; - - if (!validFormats.includes(format)) { + if (!FORMAT_NAMES.includes(format)) { res .status(400) - .json({ error: `Invalid format. Use: ${validFormats.join(", ")}` }); + .json({ error: `Invalid format. Use: ${FORMAT_NAMES.join(", ")}` }); return; } @@ -1711,8 +1713,8 @@ app.post("/api/batch-clips", async (req, res) => { return; } - if (c.format && !["vertical", "horizontal", "square"].includes(c.format)) { - res.status(400).json({ error: `Clip ${i + 1}: invalid format "${c.format}". Use: vertical, horizontal, square` }); + if (c.format && !FORMAT_NAMES.includes(c.format)) { + res.status(400).json({ error: `Clip ${i + 1}: invalid format "${c.format}". Use: ${FORMAT_NAMES.join(", ")}` }); return; } @@ -5617,10 +5619,11 @@ app.post("/api/mcp/export", async (req, res) => { // An agent that says nothing about fillers gets the studio's toggle, so an // export it triggers matches what the user set up there. - const cleanFillers = - req.body.clean_fillers !== undefined - ? req.body.clean_fillers !== false - : uiState.settings.cleanFillers !== false; + const cleanFillers = resolveCleanFillers( + req.body.clean_fillers === undefined ? undefined : req.body.clean_fillers !== false, + uiState.settings.cleanFillers !== false, + format, + ); const keepCaptionOverlay = req.body.keep_caption_overlay === true; const writeCleanVariant = req.body.write_clean_variant === true; diff --git a/src/utils/clean-fillers.test.ts b/src/utils/clean-fillers.test.ts new file mode 100644 index 0000000..5abfb2f --- /dev/null +++ b/src/utils/clean-fillers.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from "vitest"; +import { resolveCleanFillers } from "./clean-fillers.js"; + +describe("resolveCleanFillers", () => { + it("keeps the session default for the short formats", () => { + for (const format of [undefined, "vertical", "horizontal", "square"]) { + expect(resolveCleanFillers(undefined, true, format)).toBe(true); + expect(resolveCleanFillers(undefined, false, format)).toBe(false); + expect(resolveCleanFillers(undefined, undefined, format)).toBe(true); + } + }); + + it("leaves topic clips to the renderer unless asked", () => { + expect(resolveCleanFillers(undefined, true, "topic")).toBeUndefined(); + expect(resolveCleanFillers(undefined, false, "topic")).toBeUndefined(); + expect(resolveCleanFillers(undefined, undefined, "topic")).toBeUndefined(); + }); + + it("honors an explicit request on every format", () => { + expect(resolveCleanFillers(true, false, "topic")).toBe(true); + expect(resolveCleanFillers(false, true, "topic")).toBe(false); + expect(resolveCleanFillers(false, true, "vertical")).toBe(false); + expect(resolveCleanFillers(true, false, "vertical")).toBe(true); + }); +}); diff --git a/src/utils/clean-fillers.ts b/src/utils/clean-fillers.ts new file mode 100644 index 0000000..f36b689 --- /dev/null +++ b/src/utils/clean-fillers.ts @@ -0,0 +1,17 @@ +/** + * Whether a render should cut pauses and filler words out of the clip body. + * An explicit request always wins. The session default is ignored for topic + * clips, so a Studio toggle left at its default does not put micro-cuts into a + * long segment. Undefined lets the renderer apply the format's own default. + */ +export function resolveCleanFillers( + explicit: boolean | undefined, + sessionDefault: boolean | undefined, + format?: string, +): boolean | undefined { + if (explicit !== undefined) return explicit; + + if (format === "topic") return undefined; + + return sessionDefault ?? true; +} diff --git a/src/utils/clip-validation.test.ts b/src/utils/clip-validation.test.ts index 41fa660..8e34b80 100644 --- a/src/utils/clip-validation.test.ts +++ b/src/utils/clip-validation.test.ts @@ -35,10 +35,19 @@ describe("validateClipRange", () => { expect(validateClipRange(0, 301, "horizontal")).toMatch(/Max 300 seconds/); }); + it("caps topic clips at 15 minutes", () => { + expect(validateClipRange(0, 900, "topic")).toBeNull(); + expect(validateClipRange(0, 901, "topic")).toMatch(/Max 900 seconds/); + expect(validateClipRange(0, 901, "horizontal")).toMatch(/Max 300 seconds/); + }); + it("maxClipSeconds matches the range check", () => { expect(maxClipSeconds()).toBe(180); expect(maxClipSeconds("vertical")).toBe(180); + expect(maxClipSeconds("square")).toBe(180); expect(maxClipSeconds("horizontal")).toBe(300); + expect(maxClipSeconds("topic")).toBe(900); + expect(maxClipSeconds("constructor")).toBe(180); }); }); @@ -47,12 +56,17 @@ describe("validateSuggestionRange", () => { expect(validateSuggestionRange(0, 400)).toBeNull(); }); + it("accepts a topic-length range with cuts inside it", () => { + expect(validateSuggestionRange(0, 1200)).toBeNull(); + expect(validateSuggestionRange(0, 1800)).toBeNull(); + }); + it("rejects end <= start", () => { expect(validateSuggestionRange(50, 50)).toMatch(/greater than start_second/); }); it("rejects absurdly long ranges", () => { - expect(validateSuggestionRange(0, 601)).toMatch(/Max 600 seconds/); + expect(validateSuggestionRange(0, 1801)).toMatch(/Max 1800 seconds/); }); it("rejects non-numbers", () => { diff --git a/src/utils/clip-validation.ts b/src/utils/clip-validation.ts index 255d754..64abcd0 100644 --- a/src/utils/clip-validation.ts +++ b/src/utils/clip-validation.ts @@ -1,5 +1,12 @@ +const DEFAULT_MAX_CLIP_SECONDS = 180; + +const FORMAT_MAX_CLIP_SECONDS = new Map([ + ["horizontal", 300], + ["topic", 900], +]); + export function maxClipSeconds(format?: string): number { - return format === "horizontal" ? 300 : 180; + return (format && FORMAT_MAX_CLIP_SECONDS.get(format)) || DEFAULT_MAX_CLIP_SECONDS; } /** A range bound as it arrives from a request or tool call, before it is checked. */ @@ -33,7 +40,7 @@ export function validateClipRange( // Suggestions aren't bound to a format yet, so allow up to the longest // renderable duration plus trim headroom. -const MAX_SUGGESTION_SECONDS = 600; +const MAX_SUGGESTION_SECONDS = 1800; export function validateSuggestionRange(start: RangeBound, end: RangeBound): string | null { if (!isFiniteBound(start) || !isFiniteBound(end)) { diff --git a/tests/test_media_probe.py b/tests/test_media_probe.py index 1985625..a76fc8e 100644 --- a/tests/test_media_probe.py +++ b/tests/test_media_probe.py @@ -165,7 +165,7 @@ def test_cpu_flags_follow_podcli_quality(self): def test_ffmpeg_timeout_scales_with_duration(self): self.assertEqual(media_probe.ffmpeg_timeout(), 300) self.assertGreater(media_probe.ffmpeg_timeout(40), 300) - self.assertLessEqual(media_probe.ffmpeg_timeout(10_000), 1800) + self.assertLessEqual(media_probe.ffmpeg_timeout(10_000), 7200) def test_stream_durations(self): info = { diff --git a/tests/test_multicam.py b/tests/test_multicam.py index cd81f9f..f031ecd 100644 --- a/tests/test_multicam.py +++ b/tests/test_multicam.py @@ -495,6 +495,32 @@ def test_exports_point_a_second_audio_stream_at_the_right_track_not_channel_one( assert mic_asset.get("audioChannels") == "2" +def test_exports_carry_a_fifteen_minute_cut_frame_for_frame(sandbox): + cam_a = _source("cam_a.mp4", role="camera", person="host", offset=0.0, duration=900.0) + cam_b = _source("cam_b.mp4", role="camera", person="guest", offset=0.0, duration=900.0) + mic = _source("mic.mp4", kind="video", role="mic", person="host", offset=0.0, duration=900.0) + session = mc.MulticamSession( + session_id="abc123abc900", name="topic", people=[mc.Person("host", "Host"), mc.Person("guest", "Guest")], + sources=[cam_a, cam_b, mic], reference_id="mic", + cuts=[{"start": 0.0, "end": 300.0, "source_id": "cam_a"}, + {"start": 300.0, "end": 900.0, "source_id": "cam_b"}], + ) + + premiere = ET.parse(mc.export_xml(session, "premiere")).getroot() + assert premiere.findtext("./sequence/rate/timebase") == "30" + assert premiere.findtext("./sequence/duration") == "27000" + video = premiere.findall("./sequence/media/video/track/clipitem") + assert [(c.findtext("start"), c.findtext("end")) for c in video] == [("0", "9000"), ("9000", "27000")] + + fcp = ET.parse(mc.export_xml(session, "fcpxml")).getroot() + sequence = fcp.find("./library/event/project/sequence") + assert sequence.get("duration") == "900s" + assert sequence.find("./spine/gap").get("duration") == "900s" + picture = [(c.get("name"), c.get("offset"), c.get("duration")) for c in fcp.iter("asset-clip") if c.get("lane") == "1"] + assert picture == [("cam_a.mp4", "0s", "300s"), ("cam_b.mp4", "300s", "600s")] + assert {a.get("duration") for a in fcp.iter("asset")} == {"900s"} + + # --- podcli multicam ------------------------------------------------------------ def run_cli(monkeypatch, *argv): diff --git a/tests/test_topic_format.py b/tests/test_topic_format.py new file mode 100644 index 0000000..b994bd2 --- /dev/null +++ b/tests/test_topic_format.py @@ -0,0 +1,364 @@ +import contextlib +import importlib +import io +import os +import sys +import tempfile +import unittest +import xml.etree.ElementTree as ET +from pathlib import Path +from unittest import mock + +ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +BACKEND_ROOT = os.path.join(ROOT, "backend") +if BACKEND_ROOT not in sys.path: + sys.path.insert(0, BACKEND_ROOT) + +import cli as cli_mod +from services import clip_generator as cg +from services import media_probe, reel, video_cut +from services.claude_suggest import ClipBounds +from services.formats import FORMATS, get_format +from services.integrations._shared.timeline_ir import CaptionLayer, MediaClip, Project, Short +from services.integrations.davinci_resolve import emitter + +resolve_integration = importlib.import_module("services.integrations.davinci_resolve.integration") + + +class TopicFormatSpecTests(unittest.TestCase): + def test_topic_is_a_1080p_segment_between_5_and_15_minutes(self): + spec = get_format("topic") + self.assertEqual(spec.name, "topic") + self.assertEqual(spec.dims, (1920, 1080)) + self.assertFalse(spec.reframe) + self.assertEqual(spec.caption_profile, "lower_third") + self.assertEqual((spec.dur_min, spec.dur_max), (300, 900)) + self.assertEqual((spec.target_min, spec.target_max), (420, 720)) + self.assertFalse(spec.auto_tighten) + + def test_topic_framing_asks_for_setup_and_payoff(self): + spec = get_format("topic") + self.assertIn("topic segment", spec.editor) + self.assertIn("setup", spec.pacing) + self.assertIn("payoff", spec.pacing) + self.assertNotIn("SHORTER IS BETTER", spec.pacing) + + def test_existing_formats_keep_their_bounds(self): + expected = { + "vertical": (20, 45, 20, 35), + "horizontal": (60, 300, 90, 240), + "square": (20, 45, 20, 35), + } + for name, (dmin, dmax, tmin, tmax) in expected.items(): + spec = FORMATS[name] + self.assertEqual((spec.dur_min, spec.dur_max, spec.target_min, spec.target_max), (dmin, dmax, tmin, tmax)) + self.assertTrue(spec.auto_tighten, name) + + def test_topic_prompt_bounds_come_from_the_spec(self): + bounds = ClipBounds.of("topic") + self.assertEqual((bounds.dur_min, bounds.dur_max), (300, 900)) + self.assertEqual((bounds.target_min, bounds.target_max), (420, 720)) + self.assertTrue(bounds.keeps(600)) + self.assertFalse(bounds.keeps(299)) + self.assertFalse(bounds.keeps(901)) + + +class TopicFormatWiringTests(unittest.TestCase): + def _help(self, *argv): + out = io.StringIO() + with mock.patch.object(sys, "argv", ["podcli", *argv]), \ + contextlib.redirect_stdout(out), self.assertRaises(SystemExit) as raised: + cli_mod.main() + self.assertEqual(raised.exception.code, 0) + return out.getvalue() + + def test_process_and_studio_accept_topic(self): + for command in ("process", "studio"): + text = " ".join(self._help(command, "--help").split()) + self.assertIn("{vertical,horizontal,square,topic}", text, command) + + def test_cli_choices_are_the_formats_table(self): + self.assertEqual(list(FORMATS), ["vertical", "horizontal", "square", "topic"]) + + def test_unknown_format_still_falls_back_to_vertical(self): + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(get_format("nonsense").name, "vertical") + + +class RenderTimeoutScalingTests(unittest.TestCase): + def test_ffmpeg_timeout_keeps_current_values_up_to_five_minutes(self): + self.assertEqual(media_probe.ffmpeg_timeout(), 300) + self.assertEqual(media_probe.ffmpeg_timeout(40), 920) + self.assertEqual(media_probe.ffmpeg_timeout(300), 1800) + + def test_ffmpeg_timeout_grows_for_topic_length_clips(self): + self.assertEqual(media_probe.ffmpeg_timeout(600), 2400) + self.assertEqual(media_probe.ffmpeg_timeout(900), 3600) + self.assertEqual(media_probe.ffmpeg_timeout(10_000), 7200) + + def test_remotion_timeout_floor_and_scale(self): + self.assertEqual(media_probe.remotion_timeout(), 6300) + self.assertEqual(media_probe.remotion_timeout(60), 6300) + self.assertEqual(media_probe.remotion_timeout(900), 11700) + + def test_encode_duration_prefers_explicit_length(self): + cmd = ["ffmpeg", "-y", "-ss", "10", "-i", "in.mp4", "-t", "900"] + self.assertEqual(media_probe._encode_duration(cmd), 900.0) + + def test_encode_duration_probes_the_input_otherwise(self): + with mock.patch.object(media_probe, "get_media_duration_seconds", return_value=840.0) as probe: + self.assertEqual(media_probe._encode_duration(["ffmpeg", "-y", "-i", "in.mp4", "-vf", "x"]), 840.0) + probe.assert_called_once_with("in.mp4") + + def test_encode_duration_is_unknown_when_probe_finds_nothing(self): + with mock.patch.object(media_probe, "get_media_duration_seconds", return_value=0.0): + self.assertIsNone(media_probe._encode_duration(["ffmpeg", "-y", "-i", "in.mp4"])) + + def test_fallback_runner_scales_a_fit_encode_by_input_length(self): + done = mock.Mock(returncode=0, stderr="") + with mock.patch.object(media_probe, "get_media_duration_seconds", return_value=900.0), \ + mock.patch.object(media_probe, "proc_run", return_value=done) as run: + media_probe.run_ffmpeg_with_fallback( + ["ffmpeg", "-y", "-i", "in.mp4", "-vf", "scale=1920:1080"], ["-c:a", "aac"], "out.mp4", + ) + self.assertEqual(run.call_args.kwargs["timeout"], 3600) + + def test_fallback_runner_keeps_the_floor_for_short_clips(self): + done = mock.Mock(returncode=0, stderr="") + with mock.patch.object(media_probe, "get_media_duration_seconds", return_value=0.0), \ + mock.patch.object(media_probe, "proc_run", return_value=done) as run: + media_probe.run_ffmpeg_with_fallback(["ffmpeg", "-y", "-i", "in.mp4"], [], "out.mp4") + self.assertEqual(run.call_args.kwargs["timeout"], 300) + + def test_cut_segment_timeout_follows_the_cut_length(self): + done = mock.Mock(returncode=0, stderr="") + with mock.patch.object(video_cut, "proc_run", return_value=done) as run: + video_cut.cut_segment("in.mp4", "out.mp4", 100.0, 1000.0) + self.assertEqual(run.call_args.kwargs["timeout"], 3600) + video_cut.cut_segment("in.mp4", "out.mp4", 0.0, 30.0) + self.assertEqual(run.call_args.kwargs["timeout"], 720) + + def test_multi_segment_concat_timeout_follows_summed_parts(self): + done = mock.Mock(returncode=0, stderr="") + with tempfile.TemporaryDirectory() as tmp, \ + mock.patch.object(video_cut, "cut_segment"), \ + mock.patch.object(video_cut, "probe_duration", side_effect=[450.0, 450.0]), \ + mock.patch.object(video_cut, "proc_run", return_value=done) as run: + video_cut.cut_multi_segment( + "in.mp4", os.path.join(tmp, "out.mp4"), + [{"start": 0.0, "end": 450.0}, {"start": 500.0, "end": 950.0}], + ) + self.assertEqual(run.call_args.kwargs["timeout"], 3600) + + def test_reel_cut_scales_with_the_moment(self): + moment = reel.Moment(start=100.0, end=1000.0) + done = mock.Mock(returncode=0, stderr="") + with tempfile.TemporaryDirectory() as tmp, mock.patch.object(reel, "proc_run", return_value=done) as run: + reel._cut("in.mp4", tmp, 1, moment, "topic") + self.assertEqual(run.call_args.kwargs["timeout"], 3600) + reel._cut("in.mp4", tmp, 2, reel.Moment(start=0.0, end=20.0), "horizontal") + self.assertEqual(run.call_args.kwargs["timeout"], 520) + + def test_reel_concat_scales_and_keeps_the_reencode_floor(self): + session = reel.ReelSession( + session_id="topic-timeouts", source="in.mp4", profile="auto", out_dir="", format="topic", + moments=[reel.Moment(start=0.0, end=900.0, dirty=False)], + ) + calls = [] + + def fake_run(cmd, timeout, check): + calls.append(timeout) + return mock.Mock(returncode=1 if len(calls) == 1 else 0, stderr="") + + with tempfile.TemporaryDirectory() as tmp: + session.out_dir = tmp + os.makedirs(os.path.join(tmp, "clips")) + Path(tmp, "clips", "clip_01.mp4").write_bytes(b"x") + with mock.patch.object(reel, "proc_run", side_effect=fake_run), \ + mock.patch.object(reel.ReelSession, "save", return_value=""): + reel.build_reel(session) + self.assertEqual(calls, [3600, 3600]) + + calls.clear() + short = reel.ReelSession( + session_id="short-timeouts", source="in.mp4", profile="auto", out_dir="", format="horizontal", + moments=[reel.Moment(start=0.0, end=20.0, dirty=False)], + ) + with tempfile.TemporaryDirectory() as tmp: + short.out_dir = tmp + os.makedirs(os.path.join(tmp, "clips")) + Path(tmp, "clips", "clip_01.mp4").write_bytes(b"x") + with mock.patch.object(reel, "proc_run", side_effect=fake_run), \ + mock.patch.object(reel.ReelSession, "save", return_value=""): + reel.build_reel(short) + self.assertEqual(calls, [520, 900]) + + def test_remotion_call_gets_the_clip_duration(self): + captured = {} + + def fake_stream(cmd, timeout, cwd, env): + captured["timeout"] = timeout + return mock.Mock(returncode=1, stdout="", stderr="") + + with tempfile.TemporaryDirectory() as tmp: + bundle = os.path.join(tmp, "remotion", ".bundle-cache", "remotion-bundle") + os.makedirs(bundle) + Path(bundle, "index.html").write_text("x") + Path(tmp, "remotion", "render.mjs").write_text("x") + with mock.patch.dict(cg.paths, {"project_root": tmp}), \ + mock.patch.object(cg.shutil, "which", return_value="/usr/bin/node"), \ + mock.patch.object(cg, "_run_streaming", side_effect=fake_stream), \ + mock.patch.object(cg, "_report_remotion_failure"), \ + mock.patch.object(cg, "_remotion_available", None): + cg._render_with_remotion( + "in.mp4", [{"word": "a", "start": 0.0, "end": 0.5}], "branded", + os.path.join(tmp, "out.mp4"), duration=900.0, + ) + self.assertEqual(captured["timeout"], 11700) + + +class AutoFillerCutTests(unittest.TestCase): + class _Stop(Exception): + pass + + def _words(self): + return [ + {"word": f"w{i}", "start": float(i), "end": i + 0.5, "speaker": None} + for i in range(40) + ] + + def _tight_calls(self, fmt, clean_fillers, keep_segments=None): + with tempfile.NamedTemporaryFile(suffix=".mp4") as src, \ + mock.patch.object(cg, "probe_has_audio_stream", return_value=True), \ + mock.patch.object(cg, "_get_media_duration", return_value=2000.0), \ + mock.patch("services.audiogram.is_audio_only", return_value=False), \ + mock.patch.object(cg, "_build_tight_segments", + return_value=[{"start": 0, "end": 10}, {"start": 12, "end": 40}]) as tight, \ + mock.patch.object(cg.tempfile, "mkdtemp", side_effect=self._Stop), \ + self.assertRaises(self._Stop): + cg.generate_clip( + video_path=src.name, + start_second=0.0, + end_second=40.0, + format=fmt, + transcript_words=self._words(), + clean_fillers=clean_fillers, + keep_segments=keep_segments, + keep_caption_overlay=True, + ) + return tight.call_count + + def test_topic_skips_auto_cutting_by_default(self): + self.assertEqual(self._tight_calls("topic", None), 0) + self.assertEqual(self._tight_calls("topic", None, [{"start": 0.0, "end": 40.0}]), 0) + + def test_topic_cuts_when_asked_explicitly(self): + self.assertEqual(self._tight_calls("topic", True), 1) + self.assertEqual(self._tight_calls("topic", True, [{"start": 0.0, "end": 40.0}]), 1) + + def test_topic_stays_uncut_when_turned_off(self): + self.assertEqual(self._tight_calls("topic", False), 0) + + def test_other_formats_still_cut_by_default(self): + for fmt in ("vertical", "horizontal", "square"): + self.assertEqual(self._tight_calls(fmt, None), 1, fmt) + self.assertEqual(self._tight_calls(fmt, False), 0, fmt) + + +def _clip(frames, fps=30.0, name="cut.mp4"): + return MediaClip(path=Path(f"/media/{name}"), fps=fps, duration_frames=frames, width=1920, height=1080, + has_audio=True, audio_channels=2) + + +def _emit(project): + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "topic.fcpxml" + emitter.emit(project, out) + return ET.parse(out).getroot() + + +class TopicFcpxmlExportTests(unittest.TestCase): + def test_900_second_short_at_30_fps(self): + project = Project(name="Topics", fps=30.0, width=1920, height=1080, shorts=[ + Short(title="Pricing", source=_clip(27000), + captions=CaptionLayer(path=Path("/media/c.mov"), fps=30.0, duration_frames=27000)), + ]) + root = _emit(project) + + fmt = root.find("./resources/format") + self.assertEqual(fmt.get("frameDuration"), "1/30s") + self.assertEqual((fmt.get("width"), fmt.get("height")), ("1920", "1080")) + self.assertEqual(fmt.get("name"), "FFVideoFormat1920x1080p30") + + assets = {a.get("name"): a for a in root.iterfind("./resources/asset")} + self.assertEqual(assets["Pricing: source"].get("duration"), "900s") + self.assertEqual(assets["Pricing: captions"].get("duration"), "900s") + + compound = root.find("./resources/media/sequence") + self.assertEqual(compound.get("duration"), "900s") + self.assertEqual(compound.get("tcFormat"), "NDF") + main = compound.find("./spine/asset-clip") + self.assertEqual((main.get("offset"), main.get("start"), main.get("duration")), ("0s", "0s", "900s")) + self.assertEqual(main.find("video").get("duration"), "900s") + + library = root.find("./library/event/project/sequence") + self.assertEqual(library.get("duration"), "900s") + ref = library.find("./spine/ref-clip") + self.assertEqual((ref.get("offset"), ref.get("duration")), ("0s", "900s")) + + def test_caption_layer_is_clamped_or_kept_against_a_900_second_source(self): + longer = Short(title="Long", source=_clip(27000), + captions=CaptionLayer(path=Path("/media/c.mov"), fps=30.0, duration_frames=27030)) + shorter = Short(title="Short", source=_clip(27000), + captions=CaptionLayer(path=Path("/media/d.mov"), fps=30.0, duration_frames=26985)) + root = _emit(Project(name="Layers", fps=30.0, width=1920, height=1080, shorts=[longer, shorter])) + + layers = {v.get("name"): v.get("duration") for v in root.iter("video") if v.get("lane")} + self.assertEqual(layers["Long captions"], "900s") + self.assertEqual(layers["Short captions"], "1799/2s") + + def test_900_second_short_at_29_97_fps(self): + frames = round(900 * 30000 / 1001) + self.assertEqual(frames, 26973) + root = _emit(Project(name="NTSC", fps=29.97, width=1920, height=1080, + shorts=[Short(title="Topic", source=_clip(frames, fps=29.97))])) + + self.assertEqual(root.find("./resources/format").get("frameDuration"), "1001/30000s") + asset = root.find("./resources/asset") + self.assertEqual(asset.get("duration"), "8999991/10000s") + compound = root.find("./resources/media/sequence") + self.assertEqual(compound.get("duration"), "8999991/10000s") + self.assertEqual(compound.get("tcFormat"), "DF") + library = root.find("./library/event/project/sequence") + self.assertEqual(library.get("duration"), "8999991/10000s") + + def test_topic_and_short_share_one_timeline(self): + root = _emit(Project(name="Mixed", fps=30.0, width=1920, height=1080, shorts=[ + Short(title="Topic", source=_clip(27000)), + Short(title="Teaser", source=_clip(1350, name="teaser.mp4")), + ])) + + library = root.find("./library/event/project/sequence") + self.assertEqual(library.get("duration"), "945s") + refs = [(r.get("name"), r.get("offset"), r.get("duration")) for r in library.iter("ref-clip")] + self.assertEqual(refs, [("Topic", "0s", "900s"), ("Teaser", "900s", "45s")]) + + def test_resolve_tool_exports_a_900_second_clip(self): + probe = {"fps": 30.0, "duration_frames": 27000, "width": 1920, "height": 1080, + "has_audio": True, "audio_channels": 2} + with tempfile.TemporaryDirectory() as tmp, \ + mock.patch.object(resolve_integration, "probe_media", return_value=probe): + out = Path(tmp) / "nested" / "topic.fcpxml" + result = resolve_integration.integration._handle_export({ + "project_name": "Topics", "output_path": str(out), "width": 1920, "height": 1080, + "shorts": [{"title": "Pricing", "source_path": "/media/pricing.mp4"}], + }) + root = ET.parse(out).getroot() + + self.assertEqual(result["format"], "1920x1080@30.0fps") + self.assertEqual(result["shorts_count"], 1) + self.assertEqual(root.find("./library/event/project/sequence").get("duration"), "900s") + + +if __name__ == "__main__": + unittest.main()