Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions backend/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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"],
Expand Down Expand Up @@ -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)")
Expand Down
6 changes: 4 additions & 2 deletions backend/clip_studio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down Expand Up @@ -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)")
Expand All @@ -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)")
Expand Down
4 changes: 2 additions & 2 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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"),
Expand Down
8 changes: 5 additions & 3 deletions backend/services/audio_normalize.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -25,14 +25,16 @@ 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",
"-i", input_path,
"-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)

Expand Down Expand Up @@ -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
Expand Down
17 changes: 11 additions & 6 deletions backend/services/clip_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
)
Expand All @@ -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,
)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -1425,6 +1429,7 @@ def generate_clip(
font_family=font_family,
theme=theme,
captions=captions,
duration=duration,
)

if not remotion_ok and not captions:
Expand Down
18 changes: 18 additions & 0 deletions backend/services/formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class FormatSpec:
editor: str
pacing: str
lens: str
auto_tighten: bool = True

@property
def dims(self) -> tuple[int, int]:
Expand Down Expand Up @@ -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"
Expand Down
31 changes: 30 additions & 1 deletion backend/services/media_probe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)
Expand Down
9 changes: 6 additions & 3 deletions backend/services/reel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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


Expand All @@ -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
Expand Down
8 changes: 4 additions & 4 deletions backend/services/video_cut.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:]}")

Expand Down Expand Up @@ -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"
Expand Down
5 changes: 4 additions & 1 deletion remotion/render.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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) {
Expand Down
6 changes: 4 additions & 2 deletions src/handlers/batch-clips.handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -85,7 +87,7 @@ export const batchClipsToolDef = {
},
format: {
type: "string",
enum: ["vertical", "horizontal", "square"],
enum: [...FORMATS],
},
allow_ass_fallback: {
type: "boolean",
Expand Down Expand Up @@ -185,7 +187,7 @@ export async function handleBatchClips(input: BatchClipsInput): Promise<string>
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,
Expand Down
Loading
Loading