Compare commits

...

3 commits

Author SHA1 Message Date
314aa99777 feat(handoff): emit clipwright transcript + handoff manifest
Some checks failed
CI / lint-and-test (push) Successful in 17s
CI / lint-and-test (pull_request) Successful in 12s
Version bump / version-bump (pull_request) Failing after 6s
2026-10-05 16:38:02 +01:00
692df72898 docs: add growth roadmap and handoff schema 2026-10-05 16:38:02 +01:00
82c80aa49a Fixed PyAV version
All checks were successful
CI / lint-and-test (push) Successful in 11s
CI / lint-and-test (pull_request) Successful in 11s
Version bump / version-bump (pull_request) Successful in 6s
2026-09-30 19:56:06 +01:00
3 changed files with 668 additions and 38 deletions

173
PLAN.md Normal file
View file

@ -0,0 +1,173 @@
# cadence — YouTube Growth Roadmap
Working plan for the long-form editor side of the pipeline. **No code has been
written yet.** This document is the agreed spec; the authoritative handoff
interface lives here.
Related: `/home/pbento/Projects/clipwright/PLAN.md` (the packaging/clipping side).
---
## Context
**Pipeline:** raw OBS recording → **cadence** (silence/filler edit + transcript)
→ Kdenlive render (master) → **clipwright** (moments + reframe + captions +
packaging) → **Postiz** (publish).
cadence already does the hard part: transcribe (word timestamps) → `build_cuts`
→ `build_timeline` → `.kdenlive` + `.srt` + `*_llm_transcript.txt`. The render is
done manually in Kdenlive; that is the master step, so **cadence does not need a
`--render` stage.**
Inputs confirmed: OBS multitrack `.mkv`, separate audio tracks, **1440p**,
editor maximized.
### Design rules
1. **Every word carries a leading space** in the emitted transcript (cadence's
internal `Word.text` is stripped; clipwright defensively merges continuation
words). Emit `" " + text`, or document the strip-on-load fix (clipwright does
the merge on load — preferred).
2. **Timestamps are on the EDITED timeline**, absolute seconds.
3. **No network / no LLM in cadence.** Keep it a single-file, dependency-light
tool. Candidate hook/title fields are reserved but left `null`.
4. **Atomic writes** for all new outputs (reuse `_write_text_atomic`,
`cadence.py:482`).
5. **`PACING_PRESETS` stay as-is.** They are pacing only; channel identity lives
in clipwright profiles. Do not add a profile layer to cadence.
---
## #8 — cadence → clipwright handoff (emitter) · S
New `--handoff` flag (alongside `--captions`, `cadence.py:1303-1307`). After
`generate_combined_transcripts` (`cadence.py:1518`), write two files next to the
`.kdenlive` output:
```
recording.transcript.json # clipwright transcribe_media contract, edited timeline
recording.handoff.json # EDL + candidates + chapter slot
```
### `recording.transcript.json`
```json
{
"text": "full punctuated transcript",
"language": "en",
"segments": [
{
"start": 1.02, "end": 5.40, "text": "So the first thing…",
"words": [
{"word": " So", "start": 1.02, "end": 1.21},
{"word": " the", "start": 1.22, "end": 1.35}
]
}
],
"source": {"kind": "cadence-edited", "fps": 30, "width": 2560, "height": 1440,
"duration": 1234.56, "generator": "cadence 0.1.x"}
}
```
### `recording.handoff.json`
```json
{
"schema": "clipwright.handoff/1",
"generator": {"name": "cadence", "version": "0.1.x"},
"edited": {
"timeline": "voice-audio",
"fps": 30, "width": 2560, "height": 1440, "duration": 1234.56,
"jl_mode": "j", "jl_frames": 2,
"master": {"path": "recording_edited.mp4", "sha256": "…"}
},
"sources": [
{"index": 0, "path": "/abs/rec.mkv", "duration": 612.3,
"fps": 30, "width": 2560, "height": 1440,
"audio_track": 1, "audio_streams": 2}
],
"edit": [
{"source": 0, "start": 4.21, "end": 11.07, "type": "keep",
"video_shift_frames": 2},
{"source": 0, "start": 11.07, "end": 12.40, "type": "drop", "reason": "filler"}
],
"transcript": {"path": "recording.transcript.json"},
"candidates": [],
"chapters": []
}
```
### Implementation notes
- **Refactor** `generate_combined_transcripts` (`cadence.py:1121-1225`) into a
pure `build_mapped_transcript(track_data_list)` that returns
`(subs, mapped_words)`. Emit `.srt`, `*_llm_transcript.txt` **and**
`.transcript.json` from that one structure. Keeps a single chunker and makes
`tests/test_transcripts.py` cover the new emitter with no mocks.
- **`candidates[]`** stays empty in v1 (no LLM). Reserve the fields for a future
caller. When populated: `{id, start, end, word_start_idx, word_end_idx,
start_word, end_word, score, reason, tags, hook, title}`; `hook`/`title`
nullable.
- **`edit[]`** is the inverse map: per keep segment, source-relative `start`/`end`
plus optional `video_shift_frames` (J/L). Edited duration = Σ(keep.end −
keep.start).
- Paths resolved relative to the manifest's directory.
- `--handoff` implies the mapped-word computation; it does not imply `--captions`
(the point is to avoid a second ASR run downstream).
**Files:** `cadence.py` (`parse_args` `1258-1352`, `generate_combined_transcripts`
`1121-1225`, new emitter, `main` `1518`), `tests/test_transcripts.py`.
**Verify:** pure unit tests on the emitter (mapped words → segments; srt
regression unchanged; JSON round-trip). No new third-party imports.
---
## #5 — Chapters (deterministic fallback) · S–M · depends on #8
Primary home for chapter generation is **clipwright's YouTube Studio long-form
mode** (it has the Gemini plumbing). cadence's job is to supply the edited
transcript; the handoff manifest reserves a `chapters` slot.
Optional deterministic fallback in cadence: emit a `.chapters.txt`
(`00:00 Title`) from topic-shift detection over the mapped words, written from
the same `build_mapped_transcript` structure. Keep it simple; the LLM-quality
version lives in clipwright.
**Files:** `cadence.py` transcript stage; `tests/test_transcripts.py`.
---
## #9 — Loudness normalization + music ducking · DEFERRED
cadence emits a `.kdenlive` project, not media, so there is nothing to normalize
until render. With Kdenlive in the loop, the right home is **MLT filter elements
/ Kdenlive's own effects**, not a cadence render pass (which would be
render-untestable in CI).
When it lands, the recipes are already researched:
- Two-pass `loudnorm I=-14:TP=-1.0:LRA=11` (measure → apply).
- Ducking: `sidechaincompress threshold=0.03:ratio=8:attack=20:release=400`
→ `amix` → `loudnorm`.
- Voice/System tracks are already separated (`use_system`, `cadence.py:796-829`)
— a natural sidechain key.
Do not schedule this until/unless a deliberate MLT-filter or render-stage
decision is made.
---
## Tests
- Module imports nothing third-party at top level; tests run with only `pytest`.
- All I/O uses `tmp_path`; atomic writes are asserted
(`tests/test_transcripts.py:25`).
- New pure functions over `Word`/`Segment`/`VideoTrackData` are testable via the
`make_track` fixture (`tests/conftest.py:11-43`).
- CI: `.forgejo/workflows/ci.yml` (ruff + pytest).
## Open items
- Decide whether cadence's deterministic `.chapters.txt` fallback is wanted, or
chapters live only in clipwright Studio.
- #9 home decision (MLT filters vs render stage) — deferred by agreement.

View file

@ -3,6 +3,10 @@
# requires-python = ">=3.13, <3.14" # requires-python = ">=3.13, <3.14"
# dependencies = [ # dependencies = [
# "faster-whisper>=1.2.1", # "faster-whisper>=1.2.1",
# # PyAV 19 removed the `metadata_errors` kwarg that faster-whisper's
# # decode_audio() still passes (unfixed as of faster-whisper 1.2.1).
# # Pin below 19 until a release includes faster-whisper PR #1495.
# "av>=11,<19",
# "mlx-whisper>=0.4.3; platform_system == 'Darwin' and platform_machine == 'arm64'", # "mlx-whisper>=0.4.3; platform_system == 'Darwin' and platform_machine == 'arm64'",
# "nvidia-cublas-cu12; platform_system == 'Linux'", # "nvidia-cublas-cu12; platform_system == 'Linux'",
# "nvidia-cudnn-cu12; platform_system == 'Linux'", # "nvidia-cudnn-cu12; platform_system == 'Linux'",
@ -49,7 +53,7 @@ from typing import Literal
logger = logging.getLogger("cadence") logger = logging.getLogger("cadence")
__version__ = "0.1.0" __version__ = "0.1.1"
# Regex to catch elongated sounds like 'aaaa', 'uhhh', 'ummm', 'mmmm', 'eeeh', etc. # Regex to catch elongated sounds like 'aaaa', 'uhhh', 'ummm', 'mmmm', 'eeeh', etc.
HESITATION_REGEX = re.compile( HESITATION_REGEX = re.compile(
@ -118,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)
@ -629,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:
@ -644,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)
@ -655,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)
@ -1114,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)
@ -1133,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
@ -1157,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
@ -1167,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}")
@ -1208,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)
@ -1301,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,
@ -1514,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
View 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