feat(render): support multi-input concatenated --render #6

Merged
pedro-bento merged 4 commits from feat/multi-render-concat into master 2026-10-06 22:08:10 +01:00
5 changed files with 546 additions and 56 deletions

View file

@ -15,7 +15,11 @@ name: CI
# job-level `if:` and reports the skipped job as a failure instead.
on:
# Push runs only on the integration branch. A branch with an open pull
# request would otherwise run this workflow twice: once for the `push` event
# and once for the `pull_request` event.
push:
branches: [master]
pull_request:
jobs:

View file

@ -64,9 +64,9 @@ cadence recording.mp4 --preset balanced --captions
- `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.
cut decisions) instead of opening Kdenlive; with multiple inputs the kept
segments are concatenated in sequence order into one MP4. Add `--keep-project`
to also write the `.kdenlive` project.
Presets: `relaxed`, `balanced`, `punchy`. See all options with `uv run cadence.py --help`.

View file

@ -26,7 +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.
- Regenerates a native .kdenlive or MP4 output from the same cut decisions (`--render`).
- 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.
"""
@ -49,14 +49,14 @@ import tempfile
import uuid
import xml.etree.ElementTree as ET
import zipfile
from collections.abc import Callable
from collections.abc import Callable, Sequence
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Literal
logger = logging.getLogger("cadence")
__version__ = "0.2.2"
__version__ = "0.3.0"
# Regex to catch elongated sounds like 'aaaa', 'uhhh', 'ummm', 'mmmm', 'eeeh', etc.
HESITATION_REGEX = re.compile(
@ -324,6 +324,16 @@ def _align_with_whisperx(
logger.info(f"[*] Running CTC forced alignment ({align_device})...")
if isinstance(align_cache, dict) and language in align_cache:
align_model, align_meta = align_cache[language]
# The cached aligner may have been offloaded to CPU to free VRAM
# for the ASR model; whisperx.align does not move it itself.
try:
align_model.to(align_device)
except Exception:
align_model, align_meta = whisperx.load_align_model(
language_code=language, device=align_device
)
if isinstance(align_cache, dict):
align_cache[language] = (align_model, align_meta)
else:
align_model, align_meta = whisperx.load_align_model(
language_code=language, device=align_device
@ -421,6 +431,29 @@ def _release_cuda_memory() -> None:
pass
def _offload_align_cache(align_cache: dict | None) -> None:
"""Return GPU memory held by cached CTC aligners before the next ASR load.
The aligner is deliberately kept in ``align_cache`` between inputs so its
weights need not be reloaded from disk. But Whisper large-v3 and the
Wav2Vec2 aligner cannot coexist on a 6 GB card: with an earlier input's
aligner still resident, the next input's Whisper init fails with CUDA OOM
and silently drops to CPU. Moving the cached weights back to CPU keeps the
cache warm while returning VRAM to the driver; ``_align_with_whisperx``
moves them to the align device again when alignment starts. Entries that
cannot be moved are dropped so they reload from scratch.
"""
if not isinstance(align_cache, dict) or not align_cache:
return
for language, entry in list(align_cache.items()):
model = entry[0] if isinstance(entry, tuple) else entry
try:
model.to("cpu")
except Exception:
align_cache.pop(language, None)
_release_cuda_memory()
def _transcribe_faster_whisper(
wav: Path,
model_size: str,
@ -531,6 +564,11 @@ def load_or_transcribe(
if extract is not None:
extract()
# An earlier input's aligner may still be resident on the GPU; return its
# VRAM before the ASR model loads, or Whisper init OOMs and silently falls
# back to CPU (catastrophic for long recordings).
_offload_align_cache(align_cache)
logger.info(f"[*] Transcribing ({backend}) | Model: {model} | File: {video.name}")
if backend == "mlx":
@ -790,6 +828,27 @@ class RenderPlan:
return self.total_frames / self.fps
@dataclass(frozen=True, slots=True)
class MultiRenderPlan:
"""A pure description of a multi-input concatenated ffmpeg filtergraph."""
filtergraph: str
video_label: str
audio_label: str
input_count: int
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 _balanced_sum(terms: list[str]) -> str:
"""Fold ``terms`` into a balanced binary tree of ``+``.
@ -865,21 +924,24 @@ def _keep_frame_ranges(
return video_ranges, audio_ranges
def build_render_graph(
def _input_render_fragments(
td: VideoTrackData,
jl_mode: Literal["j", "l", "off"] = "j",
jl_frames: int = 2,
) -> RenderPlan:
"""Build the ffmpeg filtergraph that reproduces the MLT cut timeline.
index: int,
*,
video_label: str,
audio_label: str,
use_system: bool,
normalize: bool,
jl_mode: Literal["j", "l", "off"],
jl_frames: int,
) -> tuple[list[str], int]:
"""Filter fragments that select one input's keep ranges.
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.
Returns ``(fragments, total_frames)``. When ``normalize`` is set, the video
is forced to ``yuv420p`` and the audio to stereo fltp at 48 kHz so several
inputs can be joined with the ``concat`` filter; otherwise the source
formats pass through untouched (the historical single-input behavior).
"""
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)
@ -888,29 +950,72 @@ def build_render_graph(
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
system_stream = (
(1 if voice == 0 else 0) if use_system and 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]"
video_fmt = ",format=yuv420p" if normalize else ""
if normalize:
audio_fmt = ",aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo"
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]"
audio_fmt = ""
mix_fmt = audio_fmt or ",aformat=sample_fmts=fltp:channel_layouts=stereo"
fragments = [
f"[{index}:v:0]select='{video_expr}'{video_fmt},setpts=N/FRAME_RATE/TB{video_label}"
]
if system_stream is None:
# Single stream: pass the chosen voice track through (normalized if needed).
fragments.append(
f"[{index}:a:{voice}]aselect='{audio_expr}',asetpts=N/SR/TB{audio_fmt}{audio_label}"
)
else:
voice_label = f"[voice{index}]"
sys_label = f"[system{index}]"
fragments.append(
f"[{index}:a:{voice}]aselect='{audio_expr}',asetpts=N/SR/TB{mix_fmt}{voice_label}"
)
fragments.append(
f"[{index}:a:{system_stream}]aselect='{audio_expr}',asetpts=N/SR/TB{mix_fmt}{sys_label}"
)
fragments.append(
f"{voice_label}{sys_label}amix=inputs=2:duration=longest:normalize=0{audio_label}"
)
return fragments, total_frames
def build_render_graph(
td: VideoTrackData,
jl_mode: Literal["j", "l", "off"] = "j",
jl_frames: int = 2,
) -> RenderPlan:
"""Build the ffmpeg filtergraph that reproduces one MLT cut timeline.
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")
use_system = td.audio_stream_count >= 2
voice = td.audio_track_idx
system_stream = (1 if voice == 0 else 0) if use_system else None
audio_label = "[aout]" if use_system else "[voice]"
fragments, total_frames = _input_render_fragments(
td,
0,
video_label="[vout]",
audio_label=audio_label,
use_system=use_system,
normalize=False,
jl_mode=jl_mode,
jl_frames=jl_frames,
)
return RenderPlan(
filtergraph=";".join(chain),
filtergraph=";".join(fragments),
video_label="[vout]",
audio_label=audio_label,
voice_stream=voice,
@ -921,6 +1026,65 @@ def build_render_graph(
)
def build_multi_render_graph(
track_data_list: Sequence[VideoTrackData],
jl_mode: Literal["j", "l", "off"] = "j",
jl_frames: int = 2,
) -> MultiRenderPlan:
"""Build a filtergraph that concatenates every input's keep timeline.
Each input is selected and normalized in its own branch, then all branches
are joined with the ``concat`` filter in input order — matching the single
shared sequence the `.kdenlive` project produces for multiple inputs.
"""
if not track_data_list:
raise ValueError("cannot build a multi render graph without input tracks")
for td in track_data_list:
if not any(seg.action == "keep" for seg in td.timeline):
raise ValueError(
f"cannot build a render graph without a keep segment in {td.video.name}"
)
# Mirror `_generate_multi_kdenlive_project`: the System track is only used
# when *every* input carries a second audio stream.
use_system = all(td.audio_stream_count >= 2 for td in track_data_list)
base = track_data_list[0]
fragments: list[str] = []
concat_labels: list[str] = []
total_frames = 0
for index, td in enumerate(track_data_list):
video_label = f"[mv{index}]"
audio_label = f"[ma{index}]"
parts, frames = _input_render_fragments(
td,
index,
video_label=video_label,
audio_label=audio_label,
use_system=use_system,
normalize=True,
jl_mode=jl_mode,
jl_frames=jl_frames,
)
fragments.extend(parts)
concat_labels.append(f"{video_label}{audio_label}")
total_frames += frames
fragments.append(
f"{''.join(concat_labels)}concat=n={len(track_data_list)}:v=1:a=1[vout][aout]"
)
return MultiRenderPlan(
filtergraph=";".join(fragments),
video_label="[vout]",
audio_label="[aout]",
input_count=len(track_data_list),
total_frames=total_frames,
fps_num=base.fps_num,
fps_den=base.fps_den,
)
def build_render_command(
plan: RenderPlan,
input_video: Path,
@ -948,19 +1112,63 @@ def build_render_command(
]
def build_multi_render_command(
plan: MultiRenderPlan,
input_videos: Sequence[Path],
output: Path,
*,
filter_script: Path | None = None,
) -> list[str]:
"""Assemble the ffmpeg argv for a concatenated multi-input render."""
if filter_script is not None:
filter_args = ["-filter_complex_script", str(filter_script)]
else:
filter_args = ["-filter_complex", plan.filtergraph]
cmd = ["ffmpeg", "-y", "-hide_banner", "-loglevel", "error"]
for video in input_videos:
cmd += ["-i", str(video)]
cmd += [
*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),
]
return cmd
def render_video(
td: VideoTrackData,
tracks: VideoTrackData | Sequence[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)
) -> RenderPlan | MultiRenderPlan:
"""Render one or more inputs' keep timelines to ``output`` as an MP4.
A single track uses the historical single-``-i`` graph; multiple tracks are
normalized and concatenated in input order into one MP4.
"""
track_data_list = [tracks] if isinstance(tracks, VideoTrackData) else list(tracks)
if not track_data_list:
raise ValueError("cannot render without input tracks")
multi = len(track_data_list) > 1
if multi:
plan: RenderPlan | MultiRenderPlan = build_multi_render_graph(
track_data_list, jl_mode=jl_mode, jl_frames=jl_frames
)
else:
plan = build_render_graph(track_data_list[0], 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..."
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
@ -971,7 +1179,17 @@ def render_video(
filter_script.write_text(plan.filtergraph, encoding="utf-8")
try:
cmd = build_render_command(plan, td.video, output, filter_script=filter_script)
if multi:
cmd = build_multi_render_command(
plan,
[td.video for td in track_data_list],
output,
filter_script=filter_script,
)
else:
cmd = build_render_command(
plan, track_data_list[0].video, output, filter_script=filter_script
)
run_ff(cmd, "video render")
finally:
if filter_script is not None:
@ -1773,7 +1991,9 @@ def resolve_output_path(
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(".mp4")
return input_videos[0].with_name(f"{input_videos[0].stem}_concat.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")
@ -1837,8 +2057,8 @@ def parse_args() -> argparse.Namespace:
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."
"decisions; multiple inputs are concatenated in sequence order. "
"Skips the .kdenlive export unless --keep-project is also given."
),
)
p.add_argument(
@ -1940,12 +2160,6 @@ def main() -> None:
if not v.exists() or not v.is_file():
sys.exit(f"[!] Input file not found or invalid: {v}")
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)
@ -2062,7 +2276,7 @@ def main() -> None:
master: dict | None = None
if args.render:
render_video(
track_data_list[0],
track_data_list,
output=output,
jl_mode=args.jl_mode,
jl_frames=args.jl_frames,

View file

@ -8,6 +8,7 @@ import hashlib
import json
import shutil
import subprocess
from pathlib import Path
import pytest
@ -173,6 +174,71 @@ def test_render_graph_requires_a_keep_segment(make_track):
cadence.build_render_graph(td)
def test_multi_render_graph_concatenates_inputs(make_track):
first = make_track(
name="a.mp4",
duration=2.0,
timeline=[
Segment(0.0, 1.0, "keep"),
Segment(1.0, 1.5, "drop", reason="silence"),
Segment(1.5, 2.0, "keep"),
],
)
second = make_track(
name="b.mp4",
duration=1.0,
timeline=[Segment(0.0, 1.0, "keep")],
)
plan = cadence.build_multi_render_graph([first, second], jl_mode="off", jl_frames=0)
assert plan.input_count == 2
assert plan.total_frames == 75 # 45 + 30 frames kept
assert plan.duration == pytest.approx(2.5)
assert plan.video_label == "[vout]"
assert plan.audio_label == "[aout]"
assert "[0:v:0]" in plan.filtergraph
assert "[1:v:0]" in plan.filtergraph
assert "concat=n=2:v=1:a=1[vout][aout]" in plan.filtergraph
# Inputs are normalized so concat can join them.
assert plan.filtergraph.count("format=yuv420p") == 2
assert "sample_rates=48000" in plan.filtergraph
def test_multi_render_graph_system_audio_requires_all_inputs(make_track):
stereo = make_track(
name="a.mp4",
duration=1.0,
audio_stream_count=2,
timeline=[Segment(0.0, 1.0, "keep")],
)
mono = make_track(
name="b.mp4",
duration=1.0,
audio_stream_count=1,
timeline=[Segment(0.0, 1.0, "keep")],
)
mixed = cadence.build_multi_render_graph([stereo, mono], jl_mode="off", jl_frames=0)
assert "amix" not in mixed.filtergraph
both = cadence.build_multi_render_graph([stereo, stereo], jl_mode="off", jl_frames=0)
assert "amix=inputs=2:duration=longest:normalize=0" in both.filtergraph
assert "[0:a:1]" in both.filtergraph
assert "[1:a:1]" in both.filtergraph
def test_multi_render_graph_requires_a_keep_segment(make_track):
empty = make_track(
duration=1.0,
timeline=[Segment(0.0, 1.0, "drop", reason="silence")],
)
with pytest.raises(ValueError):
cadence.build_multi_render_graph([empty])
with pytest.raises(ValueError):
cadence.build_multi_render_graph([])
# ---------------------------------------------------------------------------
# command assembly
# ---------------------------------------------------------------------------
@ -213,6 +279,21 @@ def test_build_render_command_filter_script(make_track, tmp_path):
assert "-filter_complex" not in cmd
def test_build_multi_render_command_has_one_input_per_track(make_track, tmp_path):
first = make_track(name="a.mp4", duration=1.0, timeline=[Segment(0.0, 1.0, "keep")])
second = make_track(name="b.mp4", duration=1.0, timeline=[Segment(0.0, 1.0, "keep")])
plan = cadence.build_multi_render_graph([first, second], jl_mode="off", jl_frames=0)
out = tmp_path / "edited.mp4"
cmd = cadence.build_multi_render_command(plan, [first.video, second.video], out)
assert cmd.count("-i") == 2
assert str(first.video) in cmd
assert str(second.video) in cmd
assert cmd[cmd.index("-map") + 1] == "[vout]"
assert cmd[-1] == str(out)
# ---------------------------------------------------------------------------
# parse_args / output resolution
# ---------------------------------------------------------------------------
@ -262,6 +343,10 @@ def test_resolve_output_path_multi_input_concat(tmp_path):
cadence.resolve_output_path([first, second], None, render=False)
== tmp_path / "a_concat.kdenlive"
)
assert (
cadence.resolve_output_path([first, second], None, render=True)
== tmp_path / "a_concat.mp4"
)
# ---------------------------------------------------------------------------
@ -344,3 +429,63 @@ def test_render_video_end_to_end(tmp_path):
assert len(streams) == 1
assert streams[0]["codec_name"] == "aac"
assert streams[0]["channels"] == 2
@pytest.mark.skipif(not HAVE_FFMPEG, reason="ffmpeg/ffprobe not available")
def test_render_video_multi_end_to_end(tmp_path):
def make_source(name: str, seconds: int) -> Path:
src = tmp_path / name
subprocess.run(
[
"ffmpeg", "-y", "-loglevel", "error",
"-f", "lavfi", "-i", f"testsrc=duration={seconds}:size=320x240:rate=30",
"-f", "lavfi",
"-i", f"sine=frequency=440:sample_rate=48000:duration={seconds}",
"-c:v", "libx264", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "160k",
"-shortest", str(src),
],
check=True,
)
return src
first = make_source("first.mp4", 2)
second = make_source("second.mp4", 2)
def track(src: Path) -> cadence.VideoTrackData:
return 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"
plan = cadence.render_video([track(first), track(second)], out, jl_mode="off", jl_frames=0)
assert plan.total_frames == 90 # (30 + 15) frames kept per input
assert out.exists()
assert cadence.probe_duration(out) == pytest.approx(3.0, abs=0.2)
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

View file

@ -1,13 +1,34 @@
"""The Whisper -> CTC-aligner VRAM handoff.
"""The Whisper <-> CTC-aligner VRAM handoff.
Whisper large-v3 (~4.5 GB) and the Wav2Vec2 aligner cannot both fit on a 6 GB
GPU, which made alignment fail with ``CUBLAS_STATUS_ALLOC_FAILED``. The ASR
model must therefore be dropped and its memory released *before* alignment.
model must therefore be dropped and its memory released *before* alignment, and
a cached aligner from an earlier input must be offloaded before the next ASR
model is loaded.
"""
import sys
import types
import cadence
class _FakeAlignModel:
"""Minimal stand-in for a torch ``nn.Module`` aligner."""
def __init__(self, fail: bool = False):
self.device = "cuda"
self.fail = fail
self.calls: list[str] = []
def to(self, device):
self.calls.append(device)
if self.fail:
raise RuntimeError("cannot move")
self.device = device
return self
def test_release_cuda_memory_is_safe_without_gpu():
# Must never raise when torch is absent or no CUDA device exists: it only
# nudges the GC and (when available) torch's CUDA cache.
@ -46,3 +67,109 @@ def test_transcribe_releases_vram_before_aligning(monkeypatch, tmp_path):
# The model is gone and its memory released before the aligner is loaded.
assert events == ["transcribe", "release", "align"]
def test_offload_align_cache_moves_models_to_cpu(monkeypatch):
released = []
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: released.append(True))
model = _FakeAlignModel()
cache = {"en": (model, {"language": "en", "type": "huggingface"})}
cadence._offload_align_cache(cache)
assert model.calls == ["cpu"]
# The entry stays cached so the weights need not be reloaded from disk.
assert "en" in cache
assert released == [True]
def test_offload_align_cache_is_noop_without_entries(monkeypatch):
released = []
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: released.append(True))
cadence._offload_align_cache(None)
cadence._offload_align_cache({})
assert released == []
def test_offload_align_cache_drops_unmovable_entries(monkeypatch):
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: None)
cache = {"en": (_FakeAlignModel(fail=True), {})}
cadence._offload_align_cache(cache)
# A model that cannot be offloaded must be evicted so it reloads later.
assert cache == {}
def test_load_or_transcribe_offloads_aligner_before_transcribing(monkeypatch, tmp_path):
events = []
def fake_offload(cache):
events.append("offload")
def fake_transcribe(*args, **kwargs):
events.append("transcribe")
return [], [{"start": 0.0, "end": 1.0}]
def fake_release():
events.append("release")
def fake_align(**kwargs):
events.append("align")
return []
monkeypatch.setattr(cadence, "_cache_path", lambda *a, **k: tmp_path / "c.json")
monkeypatch.setattr(cadence, "_offload_align_cache", fake_offload)
monkeypatch.setattr(cadence, "_transcribe_faster_whisper", fake_transcribe)
monkeypatch.setattr(cadence, "_release_cuda_memory", fake_release)
monkeypatch.setattr(cadence, "_align_with_whisperx", fake_align)
monkeypatch.setattr(cadence, "_write_cache", lambda *a, **k: None)
cadence.load_or_transcribe(
video=tmp_path / "v.mp4",
wav_16k=tmp_path / "a.wav",
model="large-v3",
language="en",
track_idx=0,
no_cache=True,
backend="whisper",
align_cache={"en": (_FakeAlignModel(), {})},
)
# An earlier input's aligner is returned to CPU before this input's ASR load.
assert events == ["offload", "transcribe", "release", "align"]
def test_align_moves_cached_model_back_to_device(monkeypatch, tmp_path):
model = _FakeAlignModel()
def fake_align(raw_segments, align_model, align_meta, audio_data, device, **kwargs):
# whisperx.align never moves the model itself.
assert align_model is model
assert align_model.device == "cuda"
return {"word_segments": []}
fake_torch = types.SimpleNamespace(
cuda=types.SimpleNamespace(is_available=lambda: True),
backends=types.SimpleNamespace(mps=types.SimpleNamespace(is_available=lambda: False)),
)
fake_whisperx = types.SimpleNamespace(
load_audio=lambda path: "audio",
load_align_model=lambda **kwargs: (_ for _ in ()).throw(AssertionError("reload")),
align=fake_align,
)
monkeypatch.setitem(sys.modules, "torch", fake_torch)
monkeypatch.setitem(sys.modules, "whisperx", fake_whisperx)
words = cadence._align_with_whisperx(
raw_segments=[{"start": 0.0, "end": 1.0}],
wav_16k=tmp_path / "a.wav",
language="en",
align_cache={"en": (model, {"language": "en"})},
)
assert model.calls == ["cuda"]
assert words == []