feat/cadence-handoff #3

Merged
pedro-bento merged 3 commits from feat/cadence-handoff into master 2026-10-05 20:33:46 +01:00
4 changed files with 1169 additions and 53 deletions

View file

@ -63,6 +63,11 @@ cadence recording.mp4 --preset balanced --captions
- `recording.kdenlive` — the edited project.
- `recording.srt` and `recording_llm_transcript.txt` — generated when `--captions` is used.
Pass `--render` to have cadence encode the final `recording.mp4` itself (same
cut decisions, single input only) instead of opening Kdenlive; add
`--keep-project` to also write the `.kdenlive` project. Multi-file edits still
use the `.kdenlive` project.
Presets: `relaxed`, `balanced`, `punchy`. See all options with `uv run cadence.py --help`.
## Development

View file

@ -26,6 +26,7 @@ Features:
- Eliminates stuttered word repetitions without destroying intentional pauses.
- Frame-locked J-Cuts and L-Cuts to mask visible jump cuts without cumulative A/V drift.
- Generates a native .kdenlive project file with synchronized audio/video cuts.
- Optionally renders the final MP4 itself (`--render`) with the same cut decisions.
- Generates synced YouTube .srt captions and an LLM-ready transcript (prompt + timeline) for downstream summaries.
- Built-in pacing presets (relaxed, balanced, punchy) to eliminate the need for shell wrappers.
"""
@ -46,6 +47,7 @@ import sys
import tempfile
import uuid
import xml.etree.ElementTree as ET
import zipfile
from collections.abc import Callable
from dataclasses import asdict, dataclass
from pathlib import Path
@ -53,7 +55,7 @@ from typing import Literal
logger = logging.getLogger("cadence")
__version__ = "0.1.1"
__version__ = "0.2.0"
# Regex to catch elongated sounds like 'aaaa', 'uhhh', 'ummm', 'mmmm', 'eeeh', etc.
HESITATION_REGEX = re.compile(
@ -122,6 +124,7 @@ class Segment:
start: float
end: float
action: Literal["keep", "drop"]
reason: str | None = None
@dataclass(slots=True)
@ -633,13 +636,13 @@ def build_timeline(
timeline: list[Segment] = []
cursor = 0.0
for s, e, _ in cuts:
for s, e, reason in cuts:
s = min(max(s, 0.0), duration)
e = min(max(e, 0.0), duration)
if s > cursor:
timeline.append(Segment(start=cursor, end=s, action="keep"))
if e > s:
timeline.append(Segment(start=s, end=e, action="drop"))
timeline.append(Segment(start=s, end=e, action="drop", reason=reason))
cursor = max(cursor, e)
if cursor < duration:
@ -648,7 +651,9 @@ def build_timeline(
filtered: list[Segment] = []
for seg in timeline:
if seg.action == "keep" and (seg.end - seg.start) < min_keep_dur:
filtered.append(Segment(start=seg.start, end=seg.end, action="drop"))
filtered.append(
Segment(start=seg.start, end=seg.end, action="drop", reason="min_keep")
)
else:
filtered.append(seg)
@ -659,7 +664,10 @@ def build_timeline(
for s in filtered[1:]:
last = consolidated[-1]
if s.action == last.action:
consolidated[-1] = Segment(start=last.start, end=s.end, action=last.action)
reason = last.reason if last.reason == s.reason else "mixed"
consolidated[-1] = Segment(
start=last.start, end=s.end, action=last.action, reason=reason
)
else:
consolidated.append(s)
@ -723,6 +731,222 @@ def compute_jl_cut_shifts(
return shifts
# ---------------------------------------------------------------------------
# Render (ffmpeg) — produce the final MP4 from the same cut decisions.
# ---------------------------------------------------------------------------
# Above this many characters the filtergraph is handed to ffmpeg through a
# script file (`-filter_complex_script`) instead of the command line.
FILTERGRAPH_SCRIPT_THRESHOLD = 4000
# Exact Kdenlive export settings the render must reproduce.
RENDER_VIDEO_ARGS: tuple[str, ...] = (
"-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-g", "15", "-pix_fmt", "yuv420p",
)
RENDER_AUDIO_ARGS: tuple[str, ...] = ("-c:a", "aac", "-b:a", "160k", "-ac", "2")
RENDER_MUX_ARGS: tuple[str, ...] = ("-movflags", "+faststart", "-f", "mp4", "-threads", "0")
@dataclass(frozen=True, slots=True)
class RenderPlan:
"""A pure description of the ffmpeg filtergraph for one keep timeline."""
filtergraph: str
video_label: str
audio_label: str
voice_stream: int
system_stream: int | None
total_frames: int
fps_num: int
fps_den: int
@property
def fps(self) -> float:
return self.fps_num / self.fps_den
@property
def duration(self) -> float:
return self.total_frames / self.fps
def build_video_select_expression(ranges: list[tuple[int, int]]) -> str:
"""Inclusive source-frame ranges -> ffmpeg ``select`` expression.
Uses the decoder frame counter ``n`` so cuts land exactly on frame
boundaries regardless of floating-point timestamps.
"""
terms = [f"between(n,{start},{end})" for start, end in ranges]
return "+".join(terms) if terms else "0"
def build_audio_select_expression(ranges: list[tuple[int, int]], fps: float) -> str:
"""Inclusive source-frame ranges -> ffmpeg ``aselect`` expression.
Audio has no frame counter, so boundaries become half-open time intervals
(a frame's samples span ``[start/fps, (end+1)/fps)``), keeping every audio
segment aligned to a video frame boundary without cumulative drift.
"""
terms = []
for start, end in ranges:
t0 = start / fps
t1 = (end + 1) / fps
terms.append(f"gte(t,{t0:.9f})*lt(t,{t1:.9f})")
return "+".join(terms) if terms else "0"
def _keep_frame_ranges(
td: VideoTrackData, jl_mode: Literal["j", "l", "off"], jl_frames: int
) -> tuple[list[tuple[int, int]], list[tuple[int, int]]]:
"""(video, audio) inclusive source-frame ranges for every keep segment.
Mirrors ``_generate_multi_kdenlive_project``: each audio segment spans
``seg_dur_frames`` frames while the video segment is offset by the incoming
``shifts[k-1]`` and outgoing ``shifts[k]`` J/L shift. The two totals stay
identical because the per-boundary shifts telescope.
"""
fps = td.fps
keep_segments = [s for s in td.timeline if s.action == "keep"]
shifts = compute_jl_cut_shifts(keep_segments, fps, jl_mode=jl_mode, jl_frames=jl_frames)
video_ranges: list[tuple[int, int]] = []
audio_ranges: list[tuple[int, int]] = []
for k, seg in enumerate(keep_segments):
in_frame = int(round(seg.start * fps))
out_frame_target = int(round(seg.end * fps))
seg_dur_frames = max(1, out_frame_target - in_frame)
a_out_frame = in_frame + seg_dur_frames - 1
shift_prev = shifts[k - 1] if k > 0 else 0
shift_cur = shifts[k]
video_ranges.append((in_frame + shift_prev, a_out_frame + shift_cur))
audio_ranges.append((in_frame, a_out_frame))
return video_ranges, audio_ranges
def build_render_graph(
td: VideoTrackData,
jl_mode: Literal["j", "l", "off"] = "j",
jl_frames: int = 2,
) -> RenderPlan:
"""Build the ffmpeg filtergraph that reproduces the MLT cut timeline.
Single input only: the graph selects the kept source frames, renumbers
their timestamps, and (when the source carries a second audio stream)
mixes the Voice and System streams to stereo exactly like the MLT
Voice+System tracks.
"""
if not any(seg.action == "keep" for seg in td.timeline):
raise ValueError("cannot build a render graph without a keep segment")
video_ranges, audio_ranges = _keep_frame_ranges(td, jl_mode, jl_frames)
total_frames = sum(end - start + 1 for start, end in audio_ranges)
video_expr = build_video_select_expression(video_ranges)
audio_expr = build_audio_select_expression(audio_ranges, td.fps)
voice = td.audio_track_idx
# Mirror the MLT "System" stream pick: the *other* of streams 0/1.
system_stream = (1 if voice == 0 else 0) if td.audio_stream_count >= 2 else None
video_chain = f"[0:v:0]select='{video_expr}',setpts=N/FRAME_RATE/TB[vout]"
if system_stream is None:
# Single stream: pass the chosen voice track through untouched.
chain = [
video_chain,
f"[0:a:{voice}]aselect='{audio_expr}',asetpts=N/SR/TB[voice]",
]
audio_label = "[voice]"
else:
chain = [
video_chain,
f"[0:a:{voice}]aselect='{audio_expr}',asetpts=N/SR/TB,"
"aformat=sample_fmts=fltp:channel_layouts=stereo[voice]",
f"[0:a:{system_stream}]aselect='{audio_expr}',asetpts=N/SR/TB,"
"aformat=sample_fmts=fltp:channel_layouts=stereo[system]",
"[voice][system]amix=inputs=2:duration=longest:normalize=0[aout]",
]
audio_label = "[aout]"
return RenderPlan(
filtergraph=";".join(chain),
video_label="[vout]",
audio_label=audio_label,
voice_stream=voice,
system_stream=system_stream,
total_frames=total_frames,
fps_num=td.fps_num,
fps_den=td.fps_den,
)
def build_render_command(
plan: RenderPlan,
input_video: Path,
output: Path,
*,
filter_script: Path | None = None,
) -> list[str]:
"""Assemble the ffmpeg argv. ``filter_script`` selects the script variant."""
if filter_script is not None:
filter_args = ["-filter_complex_script", str(filter_script)]
else:
filter_args = ["-filter_complex", plan.filtergraph]
return [
"ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
"-i", str(input_video),
*filter_args,
"-map", plan.video_label,
"-map", plan.audio_label,
"-r", f"{plan.fps_num}/{plan.fps_den}",
"-fps_mode", "cfr",
*RENDER_VIDEO_ARGS,
*RENDER_AUDIO_ARGS,
*RENDER_MUX_ARGS,
str(output),
]
def render_video(
td: VideoTrackData,
output: Path,
*,
jl_mode: Literal["j", "l", "off"] = "j",
jl_frames: int = 2,
) -> RenderPlan:
"""Render ``td``'s keep timeline to ``output`` as an MP4 (single input)."""
plan = build_render_graph(td, jl_mode=jl_mode, jl_frames=jl_frames)
output.parent.mkdir(parents=True, exist_ok=True)
logger.info(
f"[*] Rendering final video: {plan.total_frames} frames "
f"({plan.duration:.2f}s) @ {plan.fps_num}/{plan.fps_den} fps..."
)
filter_script: Path | None = None
if len(plan.filtergraph) > FILTERGRAPH_SCRIPT_THRESHOLD:
fd, script_name = tempfile.mkstemp(prefix="cadence_render_", suffix=".ffgraph")
os.close(fd)
filter_script = Path(script_name)
filter_script.write_text(plan.filtergraph, encoding="utf-8")
try:
cmd = build_render_command(plan, td.video, output, filter_script=filter_script)
run_ff(cmd, "video render")
finally:
if filter_script is not None:
filter_script.unlink(missing_ok=True)
logger.info(f"[OK] Rendered video saved -> {output.name}")
return plan
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _generate_multi_kdenlive_project(
track_data_list: list[VideoTrackData],
output: Path,
@ -1118,39 +1342,51 @@ LLM_PROMPT_LINES: tuple[str, ...] = (
)
def generate_combined_transcripts(
_TERMINAL_PUNCT = frozenset({".", "?", "!"})
_CLAUSE_PUNCT = frozenset({",", ";", ":", "—", "-"})
def _format_timestamp(ts: float, is_srt: bool = True) -> str:
ts = max(0.0, ts)
ms = int(round(ts * 1000)) % 1000
s = int(ts)
h, m, sec = s // 3600, (s % 3600) // 60, s % 60
if is_srt:
return f"{h:02d}:{m:02d}:{sec:02d},{ms:03d}"
return f"{h:02d}:{m:02d}:{sec:02d}"
def build_mapped_transcript(
track_data_list: list[VideoTrackData],
output_path: Path,
*,
max_line_chars: int = 42,
max_line_words: int = 7,
max_duration_sec: float = 3.2,
min_duration_sec: float = 0.8,
max_gap_sec: float = 0.5,
) -> None:
def format_ts(ts: float, is_srt: bool = True) -> str:
ts = max(0.0, ts)
ms = int(round(ts * 1000)) % 1000
s = int(ts)
h, m, sec = s // 3600, (s % 3600) // 60, s % 60
if is_srt:
return f"{h:02d}:{m:02d}:{sec:02d},{ms:03d}"
return f"{h:02d}:{m:02d}:{sec:02d}"
) -> tuple[
list[tuple[float, float, str, list[tuple[float, float, str]]]],
list[tuple[float, float, str]],
]:
"""Chunk mapped words into subtitle lines.
The single source of truth for the ``.srt``, the LLM transcript and the
clipwright edited-transcript JSON. Returns ``(subs, mapped_words)`` where
each sub is ``(start, end, text, words)`` and each word is
``(start, end, text)`` using cadence's internal (stripped) word text. The
leading space required by the clipwright contract is applied only when
emitting JSON.
"""
mapped_words = map_words_to_edited_timeline(track_data_list)
if not mapped_words:
logger.warning("[!] No words remaining for transcript/caption generation.")
return
return [], []
subs: list[tuple[float, float, str]] = []
raw_subs: list[tuple[float, float, str, list[tuple[float, float, str]]]] = []
chunk: list[str] = []
chunk_words: list[tuple[float, float, str]] = []
chunk_start: float | None = None
prev_end: float = 0.0
terminal_punct = {".", "?", "!"}
clause_punct = {",", ";", ":", "—", "-"}
for ns, ne, text in mapped_words:
if chunk_start is None:
chunk_start = ns
@ -1161,7 +1397,7 @@ def generate_combined_transcripts(
prospective_words = len(chunk) + 1
last_char = chunk[-1][-1] if chunk and chunk[-1] else ""
has_clause_break = last_char in (terminal_punct | clause_punct)
has_clause_break = last_char in (_TERMINAL_PUNCT | _CLAUSE_PUNCT)
is_too_long = (
prospective_chars > max_line_chars
or prospective_words > max_line_words
@ -1171,33 +1407,67 @@ def generate_combined_transcripts(
if chunk and (is_too_long or is_paused or (has_clause_break and current_dur >= min_duration_sec)):
sub_end = min(ns, max(prev_end, chunk_start + min_duration_sec))
subs.append((chunk_start, sub_end, " ".join(chunk)))
raw_subs.append((chunk_start, sub_end, " ".join(chunk), list(chunk_words)))
chunk = [text]
chunk_words = [(ns, ne, text)]
chunk_start = ns
else:
chunk.append(text)
chunk_words.append((ns, ne, text))
prev_end = ne
if text and text[-1] in terminal_punct and (ne - chunk_start) >= min_duration_sec:
subs.append((chunk_start, ne, " ".join(chunk)))
if text and text[-1] in _TERMINAL_PUNCT and (ne - chunk_start) >= min_duration_sec:
raw_subs.append((chunk_start, ne, " ".join(chunk), list(chunk_words)))
chunk = []
chunk_words = []
chunk_start = None
if chunk and chunk_start is not None:
subs.append((chunk_start, max(prev_end, chunk_start + min_duration_sec), " ".join(chunk)))
raw_subs.append((
chunk_start,
max(prev_end, chunk_start + min_duration_sec),
" ".join(chunk),
list(chunk_words),
))
sanitized_subs: list[tuple[float, float, str]] = []
for i, (s, e, text) in enumerate(subs):
if sanitized_subs and s < sanitized_subs[-1][1]:
s = sanitized_subs[-1][1] + 0.01
sanitized: list[tuple[float, float, str, list[tuple[float, float, str]]]] = []
for s, e, text, words in raw_subs:
if sanitized and s < sanitized[-1][1]:
s = sanitized[-1][1] + 0.01
e = max(s + 0.1, e)
sanitized_subs.append((s, e, text))
sanitized.append((s, e, text, words))
return sanitized, mapped_words
def generate_combined_transcripts(
track_data_list: list[VideoTrackData],
output_path: Path,
*,
max_line_chars: int = 42,
max_line_words: int = 7,
max_duration_sec: float = 3.2,
min_duration_sec: float = 0.8,
max_gap_sec: float = 0.5,
) -> None:
subs, mapped_words = build_mapped_transcript(
track_data_list,
max_line_chars=max_line_chars,
max_line_words=max_line_words,
max_duration_sec=max_duration_sec,
min_duration_sec=min_duration_sec,
max_gap_sec=max_gap_sec,
)
if not mapped_words:
logger.warning("[!] No words remaining for transcript/caption generation.")
return
srt_path = output_path.with_suffix(".srt")
lines: list[str] = []
for i, (s, e, text) in enumerate(sanitized_subs, 1):
lines.extend([str(i), f"{format_ts(s)} --> {format_ts(e)}", text, ""])
for i, (s, e, text, _words) in enumerate(subs, 1):
lines.extend([str(i), f"{_format_timestamp(s)} --> {_format_timestamp(e)}", text, ""])
_write_text_atomic(srt_path, "\n".join(lines))
logger.info(f"[*] YouTube Captions generated -> {srt_path.name}")
@ -1212,19 +1482,213 @@ def generate_combined_transcripts(
para_start = ns
current_para.append(text)
time_elapsed = ne - para_start
is_sentence_end = bool(text and text[-1] in terminal_punct)
is_sentence_end = bool(text and text[-1] in _TERMINAL_PUNCT)
if (time_elapsed >= 45.0 and is_sentence_end) or time_elapsed >= 75.0:
llm_lines.append(f"[{format_ts(para_start, False)}] {' '.join(current_para)}")
llm_lines.append(f"[{_format_timestamp(para_start, False)}] {' '.join(current_para)}")
current_para = []
if current_para:
llm_lines.append(f"[{format_ts(para_start, False)}] {' '.join(current_para)}")
llm_lines.append(f"[{_format_timestamp(para_start, False)}] {' '.join(current_para)}")
_write_text_atomic(llm_transcript_path, "\n\n".join(llm_lines))
logger.info(f"[*] LLM transcript generated -> {llm_transcript_path.name}")
def _edited_duration(track_data_list: list[VideoTrackData]) -> float:
"""Total length of the edited (kept) timeline, in seconds."""
return sum(
seg.end - seg.start
for td in track_data_list
for seg in td.timeline
if seg.action == "keep"
)
def _build_transcript_payload(
track_data_list: list[VideoTrackData],
subs: list[tuple[float, float, str, list[tuple[float, float, str]]]],
language: str,
) -> dict:
"""clipwright ``transcribe_media`` contract on the EDITED timeline."""
segments: list[dict] = []
for start, end, text, words in subs:
segments.append({
"start": start,
"end": end,
"text": text,
"words": [
{"word": " " + wtext, "start": ws, "end": we}
for ws, we, wtext in words
],
})
base = track_data_list[0]
return {
"text": " ".join(seg["text"] for seg in segments if seg["text"]),
"language": language,
"segments": segments,
"source": {
"kind": "cadence-edited",
"fps": base.fps,
"width": base.width,
"height": base.height,
"duration": _edited_duration(track_data_list),
"generator": f"cadence {__version__}",
},
}
def _build_handoff_manifest(
track_data_list: list[VideoTrackData],
transcript_name: str,
*,
jl_mode: Literal["j", "l", "off"],
jl_frames: int,
master: dict | None = None,
) -> dict:
"""``clipwright.handoff/1`` manifest describing the edited timeline."""
base = track_data_list[0]
fps = base.fps
sources: list[dict] = []
for idx, td in enumerate(track_data_list):
sources.append({
"index": idx,
"path": str(td.video.resolve()),
"duration": td.duration,
"fps": td.fps,
"width": td.width,
"height": td.height,
"audio_track": td.audio_track_idx + 1,
"audio_streams": td.audio_stream_count,
})
jl_active = jl_mode != "off" and jl_frames > 0
edit: list[dict] = []
for idx, td in enumerate(track_data_list):
keep_segments = [s for s in td.timeline if s.action == "keep"]
shifts = compute_jl_cut_shifts(
keep_segments, fps, jl_mode=jl_mode, jl_frames=jl_frames
)
keep_i = 0
for seg in td.timeline:
if seg.action == "keep":
entry: dict = {
"source": idx,
"start": seg.start,
"end": seg.end,
"type": "keep",
}
if jl_active:
entry["video_shift_frames"] = shifts[keep_i]
edit.append(entry)
keep_i += 1
else:
edit.append({
"source": idx,
"start": seg.start,
"end": seg.end,
"type": "drop",
"reason": seg.reason or "edit",
})
return {
"schema": "clipwright.handoff/1",
"generator": {"name": "cadence", "version": __version__},
"edited": {
"timeline": "voice-audio",
"fps": fps,
"width": base.width,
"height": base.height,
"duration": _edited_duration(track_data_list),
"jl_mode": jl_mode,
"jl_frames": jl_frames,
"master": master,
},
"sources": sources,
"edit": edit,
"transcript": {"path": transcript_name},
"candidates": [],
"chapters": [],
}
def generate_handoff(
track_data_list: list[VideoTrackData],
output_path: Path,
*,
jl_mode: Literal["j", "l", "off"] = "j",
jl_frames: int = 2,
language: str = "en",
master: dict | None = None,
) -> None:
"""Write ``<stem>.transcript.json`` and ``<stem>.handoff.json``.
Implies the mapped-word computation (one chunker with the caption path) but
never writes the ``.srt``/LLM outputs, which stay behind ``--captions``.
"""
subs, mapped_words = build_mapped_transcript(track_data_list)
if not mapped_words:
logger.warning("[!] No words remaining for transcript/handoff generation.")
transcript_name = f"{output_path.stem}.transcript.json"
transcript_path = output_path.with_name(transcript_name)
transcript_payload = _build_transcript_payload(track_data_list, subs, language)
transcript_text = json.dumps(transcript_payload, ensure_ascii=False, indent=2)
_write_text_atomic(transcript_path, transcript_text)
logger.info(f"[*] Edited transcript generated -> {transcript_name}")
handoff = _build_handoff_manifest(
track_data_list,
transcript_name,
jl_mode=jl_mode,
jl_frames=jl_frames,
master=master,
)
handoff_name = f"{output_path.stem}.handoff.json"
handoff_path = output_path.with_name(handoff_name)
handoff_text = json.dumps(handoff, ensure_ascii=False, indent=2)
_write_text_atomic(handoff_path, handoff_text)
logger.info(f"[*] Handoff manifest generated -> {handoff_name}")
zip_name = f"{output_path.stem}.handoff.zip"
zip_path = output_path.with_name(zip_name)
_write_handoff_zip(
zip_path,
handoff_name=handoff_name,
handoff_text=handoff_text,
transcript_name=transcript_name,
transcript_text=transcript_text,
)
logger.info(f"[*] Handoff bundle generated -> {zip_name}")
def _write_handoff_zip(
zip_path: Path,
*,
handoff_name: str,
handoff_text: str,
transcript_name: str,
transcript_text: str,
) -> None:
"""Atomically bundle the loose manifest and transcript into one ZIP.
The manifest is stored under its ``*.handoff.json`` basename (what the
clipwright backend discovers) and the transcript under the exact basename
referenced by the manifest's ``transcript.path``.
"""
tmp = zip_path.with_suffix(zip_path.suffix + ".tmp")
try:
with zipfile.ZipFile(tmp, "w", compression=zipfile.ZIP_DEFLATED) as zf:
zf.writestr(handoff_name, handoff_text)
zf.writestr(transcript_name, transcript_text)
os.replace(tmp, zip_path)
except BaseException:
tmp.unlink(missing_ok=True)
raise
def _positive_int(value: str) -> int:
try:
ivalue = int(value)
@ -1255,6 +1719,24 @@ def _non_negative_float(value: str) -> float:
return fvalue
def resolve_output_path(
input_videos: list[Path], output: Path | None, *, render: bool
) -> Path:
"""Resolve the primary output path.
``--render`` targets an ``.mp4`` (default: first input stem); without it the
historical ``.kdenlive`` default is preserved.
"""
if output is not None:
resolved = output.resolve()
return resolved.with_suffix(".mp4") if render else resolved
if render:
return input_videos[0].with_suffix(".mp4")
if len(input_videos) == 1:
return input_videos[0].with_suffix(".kdenlive")
return input_videos[0].with_name(f"{input_videos[0].stem}_concat.kdenlive")
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(
description="cadence: High-retention audio-visual auto-editor for raw recordings."
@ -1280,7 +1762,10 @@ def parse_args() -> argparse.Namespace:
"-o", "--output",
type=Path,
default=None,
help="Target output path (defaults to first video path with .kdenlive suffix).",
help=(
"Target output path (defaults to first video path with .kdenlive, "
"or .mp4 when --render is used)."
),
)
p.add_argument(
"--audio-track",
@ -1305,6 +1790,28 @@ def parse_args() -> argparse.Namespace:
action="store_true",
help="Generate synced .srt subtitles and LLM packaging transcript file.",
)
p.add_argument(
"--render",
action="store_true",
help=(
"Render the final MP4 directly with ffmpeg using the same cut "
"decisions (single input only); skips the .kdenlive export unless "
"--keep-project is also given."
),
)
p.add_argument(
"--keep-project",
action="store_true",
help="With --render, also write the .kdenlive project file.",
)
p.add_argument(
"--handoff",
action="store_true",
help=(
"Generate the clipwright handoff manifest and the edited-timeline "
"transcript JSON (does not imply --captions)."
),
)
p.add_argument(
"--max-silence",
type=_non_negative_float,
@ -1391,13 +1898,13 @@ def main() -> None:
if not v.exists() or not v.is_file():
sys.exit(f"[!] Input file not found or invalid: {v}")
if args.output:
output = args.output.resolve()
else:
if len(input_videos) == 1:
output = input_videos[0].with_suffix(".kdenlive")
else:
output = input_videos[0].with_name(f"{input_videos[0].stem}_concat.kdenlive")
if args.render and len(input_videos) > 1:
sys.exit(
"[!] --render currently supports a single input file. "
"For multi-file edits, omit --render and use the generated .kdenlive project."
)
output = resolve_output_path(input_videos, args.output, render=args.render)
single_fillers = set(HESITATION_FILLERS)
if args.extra_fillers:
@ -1508,17 +2015,43 @@ def main() -> None:
output.parent.mkdir(parents=True, exist_ok=True)
_generate_multi_kdenlive_project(
track_data_list,
output=output,
jl_mode=args.jl_mode,
jl_frames=args.jl_frames,
)
master: dict | None = None
if args.render:
render_video(
track_data_list[0],
output=output,
jl_mode=args.jl_mode,
jl_frames=args.jl_frames,
)
master = {"path": str(output), "sha256": sha256_file(output)}
if args.keep_project or not args.render:
_generate_multi_kdenlive_project(
track_data_list,
output=output,
jl_mode=args.jl_mode,
jl_frames=args.jl_frames,
)
if args.captions:
generate_combined_transcripts(track_data_list, output)
logger.info(f"\n[OK] Processing complete. Master project saved to:\n {output.with_suffix('.kdenlive')}")
if args.handoff:
generate_handoff(
track_data_list,
output,
jl_mode=args.jl_mode,
jl_frames=args.jl_frames,
language=args.language,
master=master,
)
if args.render:
logger.info(f"\n[OK] Processing complete. Master video saved to:\n {output}")
else:
logger.info(
f"\n[OK] Processing complete. Master project saved to:\n {output.with_suffix('.kdenlive')}"
)
if __name__ == "__main__":

269
tests/test_handoff.py Normal file
View file

@ -0,0 +1,269 @@
import json
import zipfile
import cadence
from cadence import Segment, Word
def _timeline_with_drop():
return [
Segment(0.0, 2.0, "keep"),
Segment(2.0, 3.0, "drop", reason="filler"),
Segment(3.0, 5.0, "keep"),
]
def test_build_mapped_transcript_returns_subs_and_words(make_track):
td = make_track(
name="video.mp4",
duration=2.0,
timeline=[Segment(0.0, 2.0, "keep")],
words=[Word("Hello.", 0.2, 0.5), Word("world.", 0.6, 0.9)],
)
subs, mapped_words = cadence.build_mapped_transcript([td])
assert [w[2] for w in mapped_words] == ["Hello.", "world."]
assert len(subs) == 1
start, end, text, words = subs[0]
assert text == "Hello. world."
assert [w[2] for w in words] == ["Hello.", "world."]
assert start == 0.2
assert end >= 0.9
# Pure: a second call yields the same structure.
assert cadence.build_mapped_transcript([td]) == (subs, mapped_words)
def test_build_mapped_transcript_empty_when_no_words(make_track):
td = make_track(name="video.mp4", duration=2.0)
assert cadence.build_mapped_transcript([td]) == ([], [])
def test_generate_handoff_writes_valid_json(make_track, tmp_path):
td = make_track(
name="video.mp4",
duration=2.0,
timeline=[Segment(0.0, 2.0, "keep")],
words=[Word("Hello.", 0.2, 0.5), Word("world.", 0.6, 0.9)],
)
out = tmp_path / "recording.kdenlive"
cadence.generate_handoff([td], out, jl_mode="j", jl_frames=2, language="en")
transcript_path = tmp_path / "recording.transcript.json"
handoff_path = tmp_path / "recording.handoff.json"
assert transcript_path.exists()
assert handoff_path.exists()
assert not list(tmp_path.glob("*.tmp"))
transcript = json.loads(transcript_path.read_text(encoding="utf-8"))
handoff = json.loads(handoff_path.read_text(encoding="utf-8"))
# transcribe_media contract shape.
assert transcript["language"] == "en"
assert transcript["text"] == "Hello. world."
assert transcript["source"] == {
"kind": "cadence-edited",
"fps": 30.0,
"width": 1920,
"height": 1080,
"duration": 2.0,
"generator": f"cadence {cadence.__version__}",
}
assert len(transcript["segments"]) == 1
segment = transcript["segments"][0]
assert segment["text"] == "Hello. world."
assert set(segment) == {"start", "end", "text", "words"}
# clipwright.handoff/1 manifest.
assert handoff["schema"] == "clipwright.handoff/1"
assert handoff["generator"] == {"name": "cadence", "version": cadence.__version__}
assert handoff["edited"]["duration"] == 2.0
assert handoff["edited"]["master"] is None
assert handoff["edited"]["timeline"] == "voice-audio"
assert handoff["transcript"] == {"path": "recording.transcript.json"}
assert handoff["candidates"] == []
assert handoff["chapters"] == []
assert len(handoff["sources"]) == 1
assert handoff["sources"][0]["path"] == str((tmp_path / "video.mp4").resolve())
assert handoff["sources"][0]["audio_track"] == 1
assert [e["type"] for e in handoff["edit"]] == ["keep"]
# JSON round-trip.
assert json.loads(json.dumps(transcript)) == transcript
assert json.loads(json.dumps(handoff)) == handoff
def test_generate_handoff_writes_upload_bundle(make_track, tmp_path):
td = make_track(
name="video.mp4",
duration=2.0,
timeline=[Segment(0.0, 2.0, "keep")],
words=[Word("Hello.", 0.2, 0.5), Word("world.", 0.6, 0.9)],
)
out = tmp_path / "recording.kdenlive"
cadence.generate_handoff([td], out, jl_mode="j", jl_frames=2, language="en")
zip_path = tmp_path / "recording.handoff.zip"
assert zip_path.exists()
assert not list(tmp_path.glob("*.tmp"))
with zipfile.ZipFile(zip_path) as zf:
member_names = zf.namelist()
zipped_handoff = json.loads(zf.read("recording.handoff.json"))
zipped_transcript = json.loads(zf.read("recording.transcript.json"))
assert member_names == [
"recording.handoff.json",
"recording.transcript.json",
]
# Manifest points at the transcript member by basename.
transcript_member = zipped_handoff["transcript"]["path"]
assert transcript_member == "recording.transcript.json"
assert transcript_member in member_names
# Bundled manifest matches the loose one written alongside the ZIP.
loose_handoff = json.loads(
(tmp_path / "recording.handoff.json").read_text(encoding="utf-8")
)
loose_transcript = json.loads(
(tmp_path / "recording.transcript.json").read_text(encoding="utf-8")
)
assert zipped_handoff == loose_handoff
assert zipped_transcript == loose_transcript
def test_transcript_words_carry_leading_space(make_track, tmp_path):
td = make_track(
name="video.mp4",
duration=2.0,
timeline=[Segment(0.0, 2.0, "keep")],
words=[Word("Hello.", 0.2, 0.5), Word("world.", 0.6, 0.9)],
)
out = tmp_path / "recording.kdenlive"
cadence.generate_handoff([td], out)
transcript = json.loads(
(tmp_path / "recording.transcript.json").read_text(encoding="utf-8")
)
words = [w for seg in transcript["segments"] for w in seg["words"]]
assert words # non-empty
for word in words:
assert word["word"].startswith(" ")
assert word["word"].strip() == word["word"].lstrip()
assert [w["word"] for w in words] == [" Hello.", " world."]
def test_edited_duration_and_edit_reasons(make_track, tmp_path):
td = make_track(
name="video.mp4",
duration=5.0,
timeline=_timeline_with_drop(),
words=[
Word("a", 0.5, 0.8),
Word("dropped", 2.2, 2.5),
Word("b", 3.5, 3.8),
],
)
out = tmp_path / "recording.kdenlive"
cadence.generate_handoff([td], out, jl_mode="j", jl_frames=2)
handoff = json.loads(
(tmp_path / "recording.handoff.json").read_text(encoding="utf-8")
)
assert handoff["edited"]["duration"] == 4.0 # (2-0) + (5-3)
assert handoff["edited"]["jl_mode"] == "j"
assert handoff["edited"]["jl_frames"] == 2
edit = handoff["edit"]
assert [e["type"] for e in edit] == ["keep", "drop", "keep"]
assert edit[1]["reason"] == "filler"
assert edit[1]["start"] == 2.0
assert edit[1]["end"] == 3.0
# J/L applies: both keeps get a shift (the last is always 0).
assert edit[0]["video_shift_frames"] == 2
assert edit[2]["video_shift_frames"] == 0
def test_jl_off_omits_video_shift_frames(make_track, tmp_path):
td = make_track(
name="video.mp4",
duration=2.0,
timeline=[Segment(0.0, 2.0, "keep")],
words=[Word("Hello.", 0.2, 0.5)],
)
out = tmp_path / "recording.kdenlive"
cadence.generate_handoff([td], out, jl_mode="off", jl_frames=2)
handoff = json.loads(
(tmp_path / "recording.handoff.json").read_text(encoding="utf-8")
)
assert all("video_shift_frames" not in e for e in handoff["edit"])
def test_multi_input_concat_handoff(make_track, tmp_path):
td1 = make_track(
name="a.mp4",
duration=4.0,
timeline=[
Segment(0.0, 2.0, "keep"),
Segment(2.0, 3.0, "drop"),
Segment(3.0, 4.0, "keep"),
],
words=[Word("a", 1.0, 1.2), Word("dropped", 2.1, 2.3), Word("b", 3.1, 3.3)],
)
td2 = make_track(
name="b.mp4",
duration=3.0,
timeline=[Segment(0.0, 3.0, "keep")],
words=[Word("c", 0.5, 0.7)],
)
out = tmp_path / "recording.kdenlive"
cadence.generate_handoff([td1, td2], out)
handoff = json.loads(
(tmp_path / "recording.handoff.json").read_text(encoding="utf-8")
)
assert [s["index"] for s in handoff["sources"]] == [0, 1]
assert [s["duration"] for s in handoff["sources"]] == [4.0, 3.0]
assert handoff["edited"]["duration"] == 6.0 # (2+1) + 3
assert [e["source"] for e in handoff["edit"]] == [0, 0, 0, 1]
transcript = json.loads(
(tmp_path / "recording.transcript.json").read_text(encoding="utf-8")
)
assert transcript["source"]["duration"] == 6.0
all_words = [w["word"] for seg in transcript["segments"] for w in seg["words"]]
assert all_words == [" a", " b", " c"]
def test_srt_regression_unchanged(make_track, tmp_path):
td = make_track(
name="video.mp4",
duration=2.0,
timeline=[Segment(0.0, 2.0, "keep")],
words=[Word("Hello.", 0.2, 0.5), Word("world.", 0.6, 0.9)],
)
out = tmp_path / "recording.kdenlive"
cadence.generate_combined_transcripts([td], out)
srt = (tmp_path / "recording.srt").read_text(encoding="utf-8")
assert srt == (
"1\n"
"00:00:00,200 --> 00:00:01,000\n"
"Hello. world.\n"
)
assert (tmp_path / "recording_llm_transcript.txt").exists()
assert not list(tmp_path.glob("*.tmp"))
def test_parse_args_handoff_does_not_imply_captions(monkeypatch):
monkeypatch.setattr("sys.argv", ["cadence", "in.mp4", "--handoff"])
args = cadence.parse_args()
assert args.handoff is True
assert args.captions is False

309
tests/test_render.py Normal file
View file

@ -0,0 +1,309 @@
"""Tests for the ``--render`` stage (ffmpeg graph builder + CLI).
Pure builder/parse tests run everywhere; the integration test is skipped when
ffmpeg/ffprobe are not on ``PATH``.
"""
import hashlib
import json
import shutil
import subprocess
import pytest
import cadence
from cadence import Segment, Word
HAVE_FFMPEG = (
shutil.which("ffmpeg") is not None and shutil.which("ffprobe") is not None
)
# ---------------------------------------------------------------------------
# expression builders
# ---------------------------------------------------------------------------
def test_video_select_expression_ranges():
assert cadence.build_video_select_expression([]) == "0"
assert (
cadence.build_video_select_expression([(0, 29), (45, 59)])
== "between(n,0,29)+between(n,45,59)"
)
def test_audio_select_expression_is_half_open():
# Frame 0..29 at 30fps is the half-open interval [0s, 1s).
expr = cadence.build_audio_select_expression([(0, 29)], 30.0)
assert expr == "gte(t,0.000000000)*lt(t,1.000000000)"
assert cadence.build_audio_select_expression([], 30.0) == "0"
# ---------------------------------------------------------------------------
# graph builder
# ---------------------------------------------------------------------------
def test_render_graph_single_stream_matches_keep_segments(make_track):
td = make_track(
duration=2.0,
audio_stream_count=1,
audio_track_idx=0,
timeline=[
Segment(0.0, 1.0, "keep"),
Segment(1.0, 1.5, "drop", reason="silence"),
Segment(1.5, 2.0, "keep"),
],
)
plan = cadence.build_render_graph(td, jl_mode="off", jl_frames=0)
assert plan.voice_stream == 0
assert plan.system_stream is None
assert plan.audio_label == "[voice]"
assert plan.total_frames == 45 # 30 + 15 frames kept
assert plan.duration == pytest.approx(1.5)
assert "select='between(n,0,29)+between(n,45,59)'" in plan.filtergraph
assert "setpts=N/FRAME_RATE/TB" in plan.filtergraph
assert "asetpts=N/SR/TB" in plan.filtergraph
assert "amix" not in plan.filtergraph
def test_render_graph_system_audio_mixes_to_stereo(make_track):
td = make_track(
duration=2.0,
audio_stream_count=2,
audio_track_idx=0,
timeline=[Segment(0.0, 2.0, "keep")],
)
plan = cadence.build_render_graph(td, jl_mode="off", jl_frames=0)
assert plan.voice_stream == 0
assert plan.system_stream == 1
assert plan.audio_label == "[aout]"
assert "[0:a:0]" in plan.filtergraph
assert "[0:a:1]" in plan.filtergraph
assert "channel_layouts=stereo" in plan.filtergraph
assert "amix=inputs=2:duration=longest:normalize=0" in plan.filtergraph
def test_render_graph_system_stream_swaps_with_voice(make_track):
td = make_track(
duration=2.0,
audio_stream_count=2,
audio_track_idx=1,
timeline=[Segment(0.0, 2.0, "keep")],
)
plan = cadence.build_render_graph(td, jl_mode="off", jl_frames=0)
assert plan.voice_stream == 1
assert plan.system_stream == 0
def test_render_graph_honors_jl_shifts(make_track):
td = make_track(
duration=6.0,
fps_num=30,
fps_den=1,
timeline=[
Segment(0.0, 1.0, "keep"),
Segment(1.0, 3.0, "drop", reason="silence"),
Segment(3.0, 4.0, "keep"),
Segment(4.0, 5.0, "drop", reason="silence"),
Segment(5.0, 6.0, "keep"),
],
)
plan = cadence.build_render_graph(td, jl_mode="j", jl_frames=2)
# Each segment's video in-point inherits the *incoming* shift; the last
# segment's outgoing shift is always 0.
assert (
"select='between(n,0,31)+between(n,92,121)+between(n,152,179)'"
in plan.filtergraph
)
# J/L only redistributes frames, so total length is unchanged.
assert plan.total_frames == 90
assert plan.duration == pytest.approx(3.0)
def test_render_graph_requires_a_keep_segment(make_track):
td = make_track(
duration=2.0,
timeline=[Segment(0.0, 2.0, "drop", reason="silence")],
)
with pytest.raises(ValueError):
cadence.build_render_graph(td)
# ---------------------------------------------------------------------------
# command assembly
# ---------------------------------------------------------------------------
def test_build_render_command_uses_exact_export_settings(make_track, tmp_path):
td = make_track(
duration=1.0,
timeline=[Segment(0.0, 1.0, "keep")],
)
plan = cadence.build_render_graph(td, jl_mode="off", jl_frames=0)
out = tmp_path / "edited.mp4"
cmd = cadence.build_render_command(plan, td.video, out)
assert cmd[0] == "ffmpeg"
assert "-filter_complex" in cmd
assert "-filter_complex_script" not in cmd
assert cmd[cmd.index("-map") + 1] == "[vout]"
assert cmd[cmd.index("-r") + 1] == "30/1"
for flag in ("-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-g", "15"):
assert flag in cmd
for flag in ("-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "160k", "-ac", "2"):
assert flag in cmd
for flag in ("-movflags", "+faststart", "-f", "mp4", "-threads", "0"):
assert flag in cmd
assert cmd[-1] == str(out)
def test_build_render_command_filter_script(make_track, tmp_path):
td = make_track(duration=1.0, timeline=[Segment(0.0, 1.0, "keep")])
plan = cadence.build_render_graph(td)
script = tmp_path / "graph.txt"
cmd = cadence.build_render_command(plan, td.video, tmp_path / "o.mp4", filter_script=script)
assert "-filter_complex_script" in cmd
assert str(script) in cmd
assert "-filter_complex" not in cmd
# ---------------------------------------------------------------------------
# parse_args / output resolution
# ---------------------------------------------------------------------------
def _parse(monkeypatch, argv):
monkeypatch.setattr("sys.argv", ["cadence", *argv])
return cadence.parse_args()
def test_parse_args_render_flags(monkeypatch):
args = _parse(monkeypatch, ["video.mp4"])
assert args.render is False
assert args.keep_project is False
args = _parse(monkeypatch, ["video.mp4", "--render", "--keep-project"])
assert args.render is True
assert args.keep_project is True
def test_resolve_output_path_render_default_is_mp4(tmp_path):
video = tmp_path / "recording.mkv"
assert (
cadence.resolve_output_path([video], None, render=True)
== tmp_path / "recording.mp4"
)
# Unchanged historical default without --render.
assert (
cadence.resolve_output_path([video], None, render=False)
== tmp_path / "recording.kdenlive"
)
def test_resolve_output_path_render_forces_mp4(tmp_path):
video = tmp_path / "recording.mkv"
explicit = tmp_path / "custom.kdenlive"
assert (
cadence.resolve_output_path([video], explicit, render=True)
== tmp_path / "custom.mp4"
)
assert cadence.resolve_output_path([video], explicit, render=False) == explicit
def test_resolve_output_path_multi_input_concat(tmp_path):
first = tmp_path / "a.mp4"
second = tmp_path / "b.mp4"
assert (
cadence.resolve_output_path([first, second], None, render=False)
== tmp_path / "a_concat.kdenlive"
)
# ---------------------------------------------------------------------------
# handoff integration
# ---------------------------------------------------------------------------
def test_sha256_file(tmp_path):
path = tmp_path / "blob.bin"
path.write_bytes(b"cadence")
assert cadence.sha256_file(path) == hashlib.sha256(b"cadence").hexdigest()
def test_generate_handoff_populates_master(make_track, tmp_path):
td = make_track(
duration=1.0,
timeline=[Segment(0.0, 1.0, "keep")],
words=[Word("Hi.", 0.1, 0.3)],
)
out = tmp_path / "recording.mp4"
master = {"path": str(out), "sha256": "deadbeef"}
cadence.generate_handoff([td], out, master=master)
handoff = json.loads((tmp_path / "recording.handoff.json").read_text(encoding="utf-8"))
assert handoff["edited"]["master"] == master
# ---------------------------------------------------------------------------
# integration (ffmpeg-gated)
# ---------------------------------------------------------------------------
@pytest.mark.skipif(not HAVE_FFMPEG, reason="ffmpeg/ffprobe not available")
def test_render_video_end_to_end(tmp_path):
src = tmp_path / "src.mp4"
subprocess.run(
[
"ffmpeg", "-y", "-loglevel", "error",
"-f", "lavfi", "-i", "testsrc=duration=2:size=320x240:rate=30",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000:duration=2",
"-c:v", "libx264", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "160k",
"-shortest", str(src),
],
check=True,
)
td = cadence.VideoTrackData(
video=src,
duration=2.0,
fps_num=30,
fps_den=1,
width=320,
height=240,
audio_track_idx=0,
audio_stream_count=1,
words=[],
timeline=[
Segment(0.0, 1.0, "keep"),
Segment(1.0, 1.5, "drop", reason="silence"),
Segment(1.5, 2.0, "keep"),
],
)
out = tmp_path / "edited.mp4"
cadence.render_video(td, out, jl_mode="off", jl_frames=0)
assert out.exists()
assert out.stat().st_size > 0
assert cadence.probe_duration(out) == pytest.approx(1.5, abs=0.15)
raw = cadence.check_ff_output(
[
"ffprobe", "-v", "error", "-select_streams", "a",
"-show_entries", "stream=codec_name,channels",
"-of", "json", str(out),
],
"probe rendered audio",
)
streams = json.loads(raw)["streams"]
assert len(streams) == 1
assert streams[0]["codec_name"] == "aac"
assert streams[0]["channels"] == 2