Compare commits
No commits in common. "314aa997778d98f5496219f852c1873274afb958" and "ed8c0145ffcf6e4e0a914f689a32cd779bd79c91" have entirely different histories.
314aa99777
...
ed8c0145ff
3 changed files with 39 additions and 669 deletions
173
PLAN.md
173
PLAN.md
|
|
@ -1,173 +0,0 @@
|
|||
# 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.
|
||||
308
cadence.py
308
cadence.py
|
|
@ -3,10 +3,6 @@
|
|||
# requires-python = ">=3.13, <3.14"
|
||||
# dependencies = [
|
||||
# "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'",
|
||||
# "nvidia-cublas-cu12; platform_system == 'Linux'",
|
||||
# "nvidia-cudnn-cu12; platform_system == 'Linux'",
|
||||
|
|
@ -53,7 +49,7 @@ from typing import Literal
|
|||
|
||||
logger = logging.getLogger("cadence")
|
||||
|
||||
__version__ = "0.1.1"
|
||||
__version__ = "0.1.0"
|
||||
|
||||
# Regex to catch elongated sounds like 'aaaa', 'uhhh', 'ummm', 'mmmm', 'eeeh', etc.
|
||||
HESITATION_REGEX = re.compile(
|
||||
|
|
@ -122,7 +118,6 @@ class Segment:
|
|||
start: float
|
||||
end: float
|
||||
action: Literal["keep", "drop"]
|
||||
reason: str | None = None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
|
|
@ -634,13 +629,13 @@ def build_timeline(
|
|||
timeline: list[Segment] = []
|
||||
cursor = 0.0
|
||||
|
||||
for s, e, reason in cuts:
|
||||
for s, e, _ 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", reason=reason))
|
||||
timeline.append(Segment(start=s, end=e, action="drop"))
|
||||
cursor = max(cursor, e)
|
||||
|
||||
if cursor < duration:
|
||||
|
|
@ -649,9 +644,7 @@ 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", reason="min_keep")
|
||||
)
|
||||
filtered.append(Segment(start=seg.start, end=seg.end, action="drop"))
|
||||
else:
|
||||
filtered.append(seg)
|
||||
|
||||
|
|
@ -662,10 +655,7 @@ def build_timeline(
|
|||
for s in filtered[1:]:
|
||||
last = consolidated[-1]
|
||||
if s.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
|
||||
)
|
||||
consolidated[-1] = Segment(start=last.start, end=s.end, action=last.action)
|
||||
else:
|
||||
consolidated.append(s)
|
||||
|
||||
|
|
@ -1124,11 +1114,17 @@ LLM_PROMPT_LINES: tuple[str, ...] = (
|
|||
)
|
||||
|
||||
|
||||
_TERMINAL_PUNCT = frozenset({".", "?", "!"})
|
||||
_CLAUSE_PUNCT = frozenset({",", ";", ":", "—", "-"})
|
||||
|
||||
|
||||
def _format_timestamp(ts: float, is_srt: bool = True) -> str:
|
||||
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:
|
||||
def format_ts(ts: float, is_srt: bool = True) -> str:
|
||||
ts = max(0.0, ts)
|
||||
ms = int(round(ts * 1000)) % 1000
|
||||
s = int(ts)
|
||||
|
|
@ -1137,38 +1133,20 @@ def _format_timestamp(ts: float, is_srt: bool = True) -> str:
|
|||
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],
|
||||
*,
|
||||
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)
|
||||
if not mapped_words:
|
||||
return [], []
|
||||
|
||||
raw_subs: list[tuple[float, float, str, list[tuple[float, float, str]]]] = []
|
||||
if not mapped_words:
|
||||
logger.warning("[!] No words remaining for transcript/caption generation.")
|
||||
return
|
||||
|
||||
subs: 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
|
||||
|
|
@ -1179,7 +1157,7 @@ def build_mapped_transcript(
|
|||
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
|
||||
|
|
@ -1189,67 +1167,33 @@ def build_mapped_transcript(
|
|||
|
||||
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))
|
||||
raw_subs.append((chunk_start, sub_end, " ".join(chunk), list(chunk_words)))
|
||||
subs.append((chunk_start, sub_end, " ".join(chunk)))
|
||||
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:
|
||||
raw_subs.append((chunk_start, ne, " ".join(chunk), list(chunk_words)))
|
||||
if text and text[-1] in terminal_punct and (ne - chunk_start) >= min_duration_sec:
|
||||
subs.append((chunk_start, ne, " ".join(chunk)))
|
||||
chunk = []
|
||||
chunk_words = []
|
||||
chunk_start = None
|
||||
|
||||
if chunk and chunk_start is not None:
|
||||
raw_subs.append((
|
||||
chunk_start,
|
||||
max(prev_end, chunk_start + min_duration_sec),
|
||||
" ".join(chunk),
|
||||
list(chunk_words),
|
||||
))
|
||||
subs.append((chunk_start, max(prev_end, chunk_start + min_duration_sec), " ".join(chunk)))
|
||||
|
||||
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
|
||||
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
|
||||
e = max(s + 0.1, e)
|
||||
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
|
||||
sanitized_subs.append((s, e, text))
|
||||
|
||||
srt_path = output_path.with_suffix(".srt")
|
||||
lines: list[str] = []
|
||||
for i, (s, e, text, _words) in enumerate(subs, 1):
|
||||
lines.extend([str(i), f"{_format_timestamp(s)} --> {_format_timestamp(e)}", text, ""])
|
||||
for i, (s, e, text) in enumerate(sanitized_subs, 1):
|
||||
lines.extend([str(i), f"{format_ts(s)} --> {format_ts(e)}", text, ""])
|
||||
_write_text_atomic(srt_path, "\n".join(lines))
|
||||
logger.info(f"[*] YouTube Captions generated -> {srt_path.name}")
|
||||
|
||||
|
|
@ -1264,176 +1208,19 @@ 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_timestamp(para_start, False)}] {' '.join(current_para)}")
|
||||
llm_lines.append(f"[{format_ts(para_start, False)}] {' '.join(current_para)}")
|
||||
current_para = []
|
||||
|
||||
if current_para:
|
||||
llm_lines.append(f"[{_format_timestamp(para_start, False)}] {' '.join(current_para)}")
|
||||
llm_lines.append(f"[{format_ts(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,
|
||||
) -> 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:
|
||||
try:
|
||||
ivalue = int(value)
|
||||
|
|
@ -1514,14 +1301,6 @@ def parse_args() -> argparse.Namespace:
|
|||
action="store_true",
|
||||
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(
|
||||
"--max-silence",
|
||||
type=_non_negative_float,
|
||||
|
|
@ -1735,15 +1514,6 @@ def main() -> None:
|
|||
if args.captions:
|
||||
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')}")
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,227 +0,0 @@
|
|||
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