feat/cadence-handoff #3
2 changed files with 490 additions and 37 deletions
300
cadence.py
300
cadence.py
|
|
@ -122,6 +122,7 @@ class Segment:
|
||||||
start: float
|
start: float
|
||||||
end: float
|
end: float
|
||||||
action: Literal["keep", "drop"]
|
action: Literal["keep", "drop"]
|
||||||
|
reason: str | None = None
|
||||||
|
|
||||||
|
|
||||||
@dataclass(slots=True)
|
@dataclass(slots=True)
|
||||||
|
|
@ -633,13 +634,13 @@ def build_timeline(
|
||||||
timeline: list[Segment] = []
|
timeline: list[Segment] = []
|
||||||
cursor = 0.0
|
cursor = 0.0
|
||||||
|
|
||||||
for s, e, _ in cuts:
|
for s, e, reason in cuts:
|
||||||
s = min(max(s, 0.0), duration)
|
s = min(max(s, 0.0), duration)
|
||||||
e = min(max(e, 0.0), duration)
|
e = min(max(e, 0.0), duration)
|
||||||
if s > cursor:
|
if s > cursor:
|
||||||
timeline.append(Segment(start=cursor, end=s, action="keep"))
|
timeline.append(Segment(start=cursor, end=s, action="keep"))
|
||||||
if e > s:
|
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)
|
cursor = max(cursor, e)
|
||||||
|
|
||||||
if cursor < duration:
|
if cursor < duration:
|
||||||
|
|
@ -648,7 +649,9 @@ def build_timeline(
|
||||||
filtered: list[Segment] = []
|
filtered: list[Segment] = []
|
||||||
for seg in timeline:
|
for seg in timeline:
|
||||||
if seg.action == "keep" and (seg.end - seg.start) < min_keep_dur:
|
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:
|
else:
|
||||||
filtered.append(seg)
|
filtered.append(seg)
|
||||||
|
|
||||||
|
|
@ -659,7 +662,10 @@ def build_timeline(
|
||||||
for s in filtered[1:]:
|
for s in filtered[1:]:
|
||||||
last = consolidated[-1]
|
last = consolidated[-1]
|
||||||
if s.action == last.action:
|
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:
|
else:
|
||||||
consolidated.append(s)
|
consolidated.append(s)
|
||||||
|
|
||||||
|
|
@ -1118,17 +1124,11 @@ LLM_PROMPT_LINES: tuple[str, ...] = (
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def generate_combined_transcripts(
|
_TERMINAL_PUNCT = frozenset({".", "?", "!"})
|
||||||
track_data_list: list[VideoTrackData],
|
_CLAUSE_PUNCT = frozenset({",", ";", ":", "—", "-"})
|
||||||
output_path: Path,
|
|
||||||
*,
|
|
||||||
max_line_chars: int = 42,
|
def _format_timestamp(ts: float, is_srt: bool = True) -> str:
|
||||||
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)
|
ts = max(0.0, ts)
|
||||||
ms = int(round(ts * 1000)) % 1000
|
ms = int(round(ts * 1000)) % 1000
|
||||||
s = int(ts)
|
s = int(ts)
|
||||||
|
|
@ -1137,20 +1137,38 @@ def generate_combined_transcripts(
|
||||||
return f"{h:02d}:{m:02d}:{sec:02d},{ms:03d}"
|
return f"{h:02d}:{m:02d}:{sec:02d},{ms:03d}"
|
||||||
return f"{h:02d}:{m:02d}:{sec:02d}"
|
return f"{h:02d}:{m:02d}:{sec:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
def build_mapped_transcript(
|
||||||
|
track_data_list: list[VideoTrackData],
|
||||||
|
*,
|
||||||
|
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,
|
||||||
|
) -> 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)
|
mapped_words = map_words_to_edited_timeline(track_data_list)
|
||||||
|
|
||||||
if not mapped_words:
|
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: list[str] = []
|
||||||
|
chunk_words: list[tuple[float, float, str]] = []
|
||||||
chunk_start: float | None = None
|
chunk_start: float | None = None
|
||||||
prev_end: float = 0.0
|
prev_end: float = 0.0
|
||||||
|
|
||||||
terminal_punct = {".", "?", "!"}
|
|
||||||
clause_punct = {",", ";", ":", "—", "-"}
|
|
||||||
|
|
||||||
for ns, ne, text in mapped_words:
|
for ns, ne, text in mapped_words:
|
||||||
if chunk_start is None:
|
if chunk_start is None:
|
||||||
chunk_start = ns
|
chunk_start = ns
|
||||||
|
|
@ -1161,7 +1179,7 @@ def generate_combined_transcripts(
|
||||||
prospective_words = len(chunk) + 1
|
prospective_words = len(chunk) + 1
|
||||||
|
|
||||||
last_char = chunk[-1][-1] if chunk and chunk[-1] else ""
|
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 = (
|
is_too_long = (
|
||||||
prospective_chars > max_line_chars
|
prospective_chars > max_line_chars
|
||||||
or prospective_words > max_line_words
|
or prospective_words > max_line_words
|
||||||
|
|
@ -1171,33 +1189,67 @@ def generate_combined_transcripts(
|
||||||
|
|
||||||
if chunk and (is_too_long or is_paused or (has_clause_break and current_dur >= min_duration_sec)):
|
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))
|
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 = [text]
|
||||||
|
chunk_words = [(ns, ne, text)]
|
||||||
chunk_start = ns
|
chunk_start = ns
|
||||||
else:
|
else:
|
||||||
chunk.append(text)
|
chunk.append(text)
|
||||||
|
chunk_words.append((ns, ne, text))
|
||||||
|
|
||||||
prev_end = ne
|
prev_end = ne
|
||||||
|
|
||||||
if text and text[-1] in terminal_punct and (ne - chunk_start) >= min_duration_sec:
|
if text and text[-1] in _TERMINAL_PUNCT and (ne - chunk_start) >= min_duration_sec:
|
||||||
subs.append((chunk_start, ne, " ".join(chunk)))
|
raw_subs.append((chunk_start, ne, " ".join(chunk), list(chunk_words)))
|
||||||
chunk = []
|
chunk = []
|
||||||
|
chunk_words = []
|
||||||
chunk_start = None
|
chunk_start = None
|
||||||
|
|
||||||
if chunk and chunk_start is not 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]] = []
|
sanitized: list[tuple[float, float, str, list[tuple[float, float, str]]]] = []
|
||||||
for i, (s, e, text) in enumerate(subs):
|
for s, e, text, words in raw_subs:
|
||||||
if sanitized_subs and s < sanitized_subs[-1][1]:
|
if sanitized and s < sanitized[-1][1]:
|
||||||
s = sanitized_subs[-1][1] + 0.01
|
s = sanitized[-1][1] + 0.01
|
||||||
e = max(s + 0.1, e)
|
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")
|
srt_path = output_path.with_suffix(".srt")
|
||||||
lines: list[str] = []
|
lines: list[str] = []
|
||||||
for i, (s, e, text) in enumerate(sanitized_subs, 1):
|
for i, (s, e, text, _words) in enumerate(subs, 1):
|
||||||
lines.extend([str(i), f"{format_ts(s)} --> {format_ts(e)}", text, ""])
|
lines.extend([str(i), f"{_format_timestamp(s)} --> {_format_timestamp(e)}", text, ""])
|
||||||
_write_text_atomic(srt_path, "\n".join(lines))
|
_write_text_atomic(srt_path, "\n".join(lines))
|
||||||
logger.info(f"[*] YouTube Captions generated -> {srt_path.name}")
|
logger.info(f"[*] YouTube Captions generated -> {srt_path.name}")
|
||||||
|
|
||||||
|
|
@ -1212,19 +1264,176 @@ def generate_combined_transcripts(
|
||||||
para_start = ns
|
para_start = ns
|
||||||
current_para.append(text)
|
current_para.append(text)
|
||||||
time_elapsed = ne - para_start
|
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:
|
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 = []
|
current_para = []
|
||||||
|
|
||||||
if 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))
|
_write_text_atomic(llm_transcript_path, "\n\n".join(llm_lines))
|
||||||
logger.info(f"[*] LLM transcript generated -> {llm_transcript_path.name}")
|
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,
|
||||||
|
) -> 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": None,
|
||||||
|
},
|
||||||
|
"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",
|
||||||
|
) -> 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)
|
||||||
|
_write_text_atomic(
|
||||||
|
transcript_path, json.dumps(transcript_payload, ensure_ascii=False, indent=2)
|
||||||
|
)
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
handoff_name = f"{output_path.stem}.handoff.json"
|
||||||
|
handoff_path = output_path.with_name(handoff_name)
|
||||||
|
_write_text_atomic(
|
||||||
|
handoff_path, json.dumps(handoff, ensure_ascii=False, indent=2)
|
||||||
|
)
|
||||||
|
logger.info(f"[*] Handoff manifest generated -> {handoff_name}")
|
||||||
|
|
||||||
|
|
||||||
def _positive_int(value: str) -> int:
|
def _positive_int(value: str) -> int:
|
||||||
try:
|
try:
|
||||||
ivalue = int(value)
|
ivalue = int(value)
|
||||||
|
|
@ -1305,6 +1514,14 @@ def parse_args() -> argparse.Namespace:
|
||||||
action="store_true",
|
action="store_true",
|
||||||
help="Generate synced .srt subtitles and LLM packaging transcript file.",
|
help="Generate synced .srt subtitles and LLM packaging transcript 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(
|
p.add_argument(
|
||||||
"--max-silence",
|
"--max-silence",
|
||||||
type=_non_negative_float,
|
type=_non_negative_float,
|
||||||
|
|
@ -1518,6 +1735,15 @@ def main() -> None:
|
||||||
if args.captions:
|
if args.captions:
|
||||||
generate_combined_transcripts(track_data_list, output)
|
generate_combined_transcripts(track_data_list, output)
|
||||||
|
|
||||||
|
if args.handoff:
|
||||||
|
generate_handoff(
|
||||||
|
track_data_list,
|
||||||
|
output,
|
||||||
|
jl_mode=args.jl_mode,
|
||||||
|
jl_frames=args.jl_frames,
|
||||||
|
language=args.language,
|
||||||
|
)
|
||||||
|
|
||||||
logger.info(f"\n[OK] Processing complete. Master project saved to:\n {output.with_suffix('.kdenlive')}")
|
logger.info(f"\n[OK] Processing complete. Master project saved to:\n {output.with_suffix('.kdenlive')}")
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
227
tests/test_handoff.py
Normal file
227
tests/test_handoff.py
Normal file
|
|
@ -0,0 +1,227 @@
|
||||||
|
import json
|
||||||
|
|
||||||
|
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_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
|
||||||
Loading…
Reference in a new issue