Compare commits
3 commits
70198e0a75
...
7949903c89
| Author | SHA1 | Date | |
|---|---|---|---|
| 7949903c89 | |||
| 1718b95261 | |||
| 7a96bd8970 |
3 changed files with 256 additions and 22 deletions
11
README.md
11
README.md
|
|
@ -68,7 +68,16 @@ cut decisions) instead of opening Kdenlive; with multiple inputs the kept
|
||||||
segments are concatenated in sequence order into one MP4. Add `--keep-project`
|
segments are concatenated in sequence order into one MP4. Add `--keep-project`
|
||||||
to also write the `.kdenlive` project.
|
to also write the `.kdenlive` project.
|
||||||
|
|
||||||
Presets: `relaxed`, `balanced`, `punchy`. See all options with `uv run cadence.py --help`.
|
Presets: `super-relaxed`, `relaxed`, `balanced`, `punchy`. See all options with `uv run cadence.py --help`.
|
||||||
|
|
||||||
|
## GPU notes (Linux / NVIDIA)
|
||||||
|
|
||||||
|
Transcription is memory-lean and degrades instead of crashing: cadence starts
|
||||||
|
with `int8_float16` and, if CTranslate2 still runs out of VRAM partway through a
|
||||||
|
long file (common with `large-v3` on a 6 GB card), it drops and releases the
|
||||||
|
model and retries with `int8` + greedy decoding before finally falling back to
|
||||||
|
CPU. When unset, `CT2_CUDA_ALLOCATOR=cub_caching` is selected for a more robust
|
||||||
|
allocator.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
|
|
|
||||||
132
cadence.py
132
cadence.py
|
|
@ -28,7 +28,7 @@ Features:
|
||||||
- Generates a native .kdenlive project file with synchronized audio/video cuts.
|
- Generates a native .kdenlive project file with synchronized audio/video cuts.
|
||||||
- Regenerates a native .kdenlive or MP4 output from the same cut decisions (`--render`).
|
- 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.
|
- 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.
|
- Built-in pacing presets (super-relaxed, relaxed, balanced, punchy) to eliminate the need for shell wrappers.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
@ -56,7 +56,7 @@ from typing import Literal
|
||||||
|
|
||||||
logger = logging.getLogger("cadence")
|
logger = logging.getLogger("cadence")
|
||||||
|
|
||||||
__version__ = "0.3.0"
|
__version__ = "0.3.2"
|
||||||
|
|
||||||
# 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(
|
||||||
|
|
@ -79,6 +79,12 @@ DISCOURSE_FILLERS = {
|
||||||
|
|
||||||
# Built-in pacing profiles to eliminate shell script wrappers
|
# Built-in pacing profiles to eliminate shell script wrappers
|
||||||
PACING_PRESETS = {
|
PACING_PRESETS = {
|
||||||
|
"super-relaxed": {
|
||||||
|
"max_silence": 1.25,
|
||||||
|
"pad": 0.25,
|
||||||
|
"min_keep": 0.10,
|
||||||
|
"jl_frames": 0,
|
||||||
|
},
|
||||||
"relaxed": {
|
"relaxed": {
|
||||||
"max_silence": 0.85,
|
"max_silence": 0.85,
|
||||||
"pad": 0.15,
|
"pad": 0.15,
|
||||||
|
|
@ -112,6 +118,16 @@ VERBATIM_PROMPT = (
|
||||||
"Verbatim transcription with all hesitations, stutters, and verbal fillers like um, uh, er."
|
"Verbatim transcription with all hesitations, stutters, and verbal fillers like um, uh, er."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# faster-whisper / CTranslate2 GPU configs tried in order when transcription
|
||||||
|
# runs out of VRAM. large-v3 in float16 needs ~4.5 GB, which leaves a 6 GB card
|
||||||
|
# no headroom for decoder spikes, so we start memory-lean and step down on OOM.
|
||||||
|
# Each tuple is (device, compute_type, beam_size).
|
||||||
|
FASTER_WHISPER_FALLBACKS: tuple[tuple[str, str, int], ...] = (
|
||||||
|
("cuda", "int8_float16", 5),
|
||||||
|
("cuda", "int8", 1),
|
||||||
|
("cpu", "int8", 1),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
class Word:
|
class Word:
|
||||||
|
|
@ -397,18 +413,42 @@ def _transcribe_mlx(
|
||||||
return words, raw_segments
|
return words, raw_segments
|
||||||
|
|
||||||
|
|
||||||
def _load_faster_whisper_model(model_size: str):
|
def _configure_ct2_cuda_allocator() -> None:
|
||||||
|
"""Prefer CTranslate2's caching CUDA allocator.
|
||||||
|
|
||||||
|
CTranslate2's default ``cuda_malloc_async`` allocator can surface spurious
|
||||||
|
"CUDA failed with error out of memory" errors under fragmentation or memory
|
||||||
|
pressure (OpenNMT/CTranslate2#690); ``cub_caching`` reuses freed blocks and
|
||||||
|
is more robust across a long transcription. Must be set before
|
||||||
|
``ctranslate2``/``faster_whisper`` is imported.
|
||||||
|
"""
|
||||||
|
if platform.system() == "Linux":
|
||||||
|
os.environ.setdefault("CT2_CUDA_ALLOCATOR", "cub_caching")
|
||||||
|
|
||||||
|
|
||||||
|
def _load_faster_whisper_model(
|
||||||
|
model_size: str,
|
||||||
|
device: str | None = None,
|
||||||
|
compute_type: str | None = None,
|
||||||
|
):
|
||||||
|
_configure_ct2_cuda_allocator()
|
||||||
preload_nvidia_libs()
|
preload_nvidia_libs()
|
||||||
from faster_whisper import WhisperModel
|
from faster_whisper import WhisperModel
|
||||||
|
|
||||||
target_device = "cuda" if platform.system() == "Linux" else "cpu"
|
if device is None:
|
||||||
target_compute = "float16" if target_device == "cuda" else "int8"
|
# Default path keeps the historical CPU fallback when GPU init fails.
|
||||||
|
device = "cuda" if platform.system() == "Linux" else "cpu"
|
||||||
|
compute_type = compute_type or ("int8_float16" if device == "cuda" else "int8")
|
||||||
|
try:
|
||||||
|
return WhisperModel(model_size, device=device, compute_type=compute_type)
|
||||||
|
except Exception as e:
|
||||||
|
if device == "cpu":
|
||||||
|
raise
|
||||||
|
logger.info(f"[*] {device.upper()} init failed ({e}), falling back to CPU.")
|
||||||
|
return WhisperModel(model_size, device="cpu", compute_type="int8")
|
||||||
|
|
||||||
try:
|
# Explicit device/compute_type (fallback ladder): honour it strictly.
|
||||||
return WhisperModel(model_size, device=target_device, compute_type=target_compute)
|
return WhisperModel(model_size, device=device, compute_type=compute_type or "int8")
|
||||||
except Exception as e:
|
|
||||||
logger.info(f"[*] {target_device.upper()} init failed ({e}), falling back to CPU.")
|
|
||||||
return WhisperModel(model_size, device="cpu", compute_type="int8")
|
|
||||||
|
|
||||||
|
|
||||||
def _release_cuda_memory() -> None:
|
def _release_cuda_memory() -> None:
|
||||||
|
|
@ -454,23 +494,26 @@ def _offload_align_cache(align_cache: dict | None) -> None:
|
||||||
_release_cuda_memory()
|
_release_cuda_memory()
|
||||||
|
|
||||||
|
|
||||||
def _transcribe_faster_whisper(
|
def _is_cuda_oom(exc: BaseException) -> bool:
|
||||||
wav: Path,
|
"""True for CTranslate2's CUDA allocation failures (not torch OOM)."""
|
||||||
model_size: str,
|
return "out of memory" in str(exc).lower()
|
||||||
language: str = "en",
|
|
||||||
model=None,
|
|
||||||
) -> tuple[list[Word], list[dict]]:
|
|
||||||
from tqdm import tqdm
|
|
||||||
|
|
||||||
if model is None:
|
|
||||||
model = _load_faster_whisper_model(model_size)
|
def _run_faster_whisper(
|
||||||
|
wav: Path,
|
||||||
|
model,
|
||||||
|
language: str,
|
||||||
|
beam_size: int,
|
||||||
|
) -> tuple[list[Word], list[dict]]:
|
||||||
|
"""Consume one WhisperModel's segment generator into words + raw segments."""
|
||||||
|
from tqdm import tqdm
|
||||||
|
|
||||||
segments, meta = model.transcribe(
|
segments, meta = model.transcribe(
|
||||||
str(wav),
|
str(wav),
|
||||||
language=language,
|
language=language,
|
||||||
word_timestamps=True,
|
word_timestamps=True,
|
||||||
vad_filter=False,
|
vad_filter=False,
|
||||||
beam_size=5,
|
beam_size=beam_size,
|
||||||
condition_on_previous_text=False,
|
condition_on_previous_text=False,
|
||||||
initial_prompt=VERBATIM_PROMPT,
|
initial_prompt=VERBATIM_PROMPT,
|
||||||
)
|
)
|
||||||
|
|
@ -501,6 +544,53 @@ def _transcribe_faster_whisper(
|
||||||
return words, raw_segments
|
return words, raw_segments
|
||||||
|
|
||||||
|
|
||||||
|
def _transcribe_faster_whisper(
|
||||||
|
wav: Path,
|
||||||
|
model_size: str,
|
||||||
|
language: str = "en",
|
||||||
|
model=None,
|
||||||
|
) -> tuple[list[Word], list[dict]]:
|
||||||
|
"""Transcribe with faster-whisper, stepping down VRAM usage on CUDA OOM.
|
||||||
|
|
||||||
|
When ``model`` is supplied it is used as-is (dependency injection/tests).
|
||||||
|
Otherwise the ``FASTER_WHISPER_FALLBACKS`` ladder is walked: on a CUDA out-of-
|
||||||
|
memory error the current model is dropped, its memory released, and the next,
|
||||||
|
smaller-footprint config is tried from scratch. The last error is re-raised
|
||||||
|
only after every fallback has failed.
|
||||||
|
"""
|
||||||
|
if model is not None:
|
||||||
|
return _run_faster_whisper(wav, model, language, beam_size=5)
|
||||||
|
|
||||||
|
last_exc: BaseException | None = None
|
||||||
|
for device, compute_type, beam_size in FASTER_WHISPER_FALLBACKS:
|
||||||
|
try:
|
||||||
|
attempt_model = _load_faster_whisper_model(
|
||||||
|
model_size, device=device, compute_type=compute_type
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
last_exc = e
|
||||||
|
logger.warning(f"[!] faster-whisper init failed on {device}/{compute_type}: {e}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
return _run_faster_whisper(wav, attempt_model, language, beam_size=beam_size)
|
||||||
|
except RuntimeError as e:
|
||||||
|
if not _is_cuda_oom(e):
|
||||||
|
raise
|
||||||
|
last_exc = e
|
||||||
|
logger.warning(
|
||||||
|
f"[!] Out of VRAM transcribing with {device}/{compute_type} "
|
||||||
|
f"(beam_size={beam_size}); retrying with a smaller footprint..."
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
del attempt_model
|
||||||
|
_release_cuda_memory()
|
||||||
|
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Transcription failed on every fallback for {wav.name}: {last_exc}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _cache_key(model: str, backend: str, language: str) -> str:
|
def _cache_key(model: str, backend: str, language: str) -> str:
|
||||||
return hashlib.sha256(
|
return hashlib.sha256(
|
||||||
json.dumps([backend, language, model]).encode()
|
json.dumps([backend, language, model]).encode()
|
||||||
|
|
@ -2016,7 +2106,7 @@ def parse_args() -> argparse.Namespace:
|
||||||
)
|
)
|
||||||
p.add_argument(
|
p.add_argument(
|
||||||
"--preset",
|
"--preset",
|
||||||
choices=["relaxed", "balanced", "punchy"],
|
choices=["super-relaxed", "relaxed", "balanced", "punchy"],
|
||||||
default=None,
|
default=None,
|
||||||
help="Apply built-in editing pacing settings (overrides defaults).",
|
help="Apply built-in editing pacing settings (overrides defaults).",
|
||||||
)
|
)
|
||||||
|
|
|
||||||
135
tests/test_whisper_fallback.py
Normal file
135
tests/test_whisper_fallback.py
Normal file
|
|
@ -0,0 +1,135 @@
|
||||||
|
"""CUDA OOM fallback for faster-whisper transcription.
|
||||||
|
|
||||||
|
faster-whisper large-v3 in float16 needs ~4.5 GB, leaving a 6 GB card no
|
||||||
|
headroom for CTranslate2 decoder spikes, so a long transcription can die
|
||||||
|
partway through with ``CUDA failed with error out of memory``. The loader must
|
||||||
|
start memory-lean and ``_transcribe_faster_whisper`` must step down a fallback
|
||||||
|
ladder (dropping and releasing each model) instead of aborting.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import types
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import cadence
|
||||||
|
|
||||||
|
|
||||||
|
def test_is_cuda_oom_classifies_allocation_failures():
|
||||||
|
assert cadence._is_cuda_oom(RuntimeError("CUDA failed with error out of memory"))
|
||||||
|
assert cadence._is_cuda_oom(RuntimeError("out of memory"))
|
||||||
|
assert not cadence._is_cuda_oom(RuntimeError("boom"))
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_model_defaults_to_memory_lean_cuda(monkeypatch):
|
||||||
|
monkeypatch.delenv("CT2_CUDA_ALLOCATOR", raising=False)
|
||||||
|
monkeypatch.setattr(cadence.platform, "system", lambda: "Linux")
|
||||||
|
|
||||||
|
calls: list[tuple[str, dict]] = []
|
||||||
|
|
||||||
|
class _FakeWhisperModel:
|
||||||
|
def __init__(self, model_size, **kwargs):
|
||||||
|
calls.append((model_size, kwargs))
|
||||||
|
|
||||||
|
fake_module = types.SimpleNamespace(WhisperModel=_FakeWhisperModel)
|
||||||
|
monkeypatch.setitem(sys.modules, "faster_whisper", fake_module)
|
||||||
|
|
||||||
|
cadence._load_faster_whisper_model("large-v3")
|
||||||
|
|
||||||
|
assert calls == [("large-v3", {"device": "cuda", "compute_type": "int8_float16"})]
|
||||||
|
assert os.environ["CT2_CUDA_ALLOCATOR"] == "cub_caching"
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_model_honours_explicit_device(monkeypatch):
|
||||||
|
monkeypatch.setattr(cadence.platform, "system", lambda: "Linux")
|
||||||
|
|
||||||
|
calls: list[tuple[str, dict]] = []
|
||||||
|
|
||||||
|
class _FakeWhisperModel:
|
||||||
|
def __init__(self, model_size, **kwargs):
|
||||||
|
calls.append((model_size, kwargs))
|
||||||
|
|
||||||
|
fake_module = types.SimpleNamespace(WhisperModel=_FakeWhisperModel)
|
||||||
|
monkeypatch.setitem(sys.modules, "faster_whisper", fake_module)
|
||||||
|
|
||||||
|
cadence._load_faster_whisper_model("large-v3", device="cpu", compute_type="int8")
|
||||||
|
|
||||||
|
# No silent substitution: the explicit config is passed straight through.
|
||||||
|
assert calls == [("large-v3", {"device": "cpu", "compute_type": "int8"})]
|
||||||
|
|
||||||
|
|
||||||
|
def test_transcribe_steps_down_ladder_on_cuda_oom(monkeypatch):
|
||||||
|
attempts: list[tuple[str, str]] = []
|
||||||
|
runs = {"n": 0}
|
||||||
|
|
||||||
|
def fake_load(model_size, device=None, compute_type=None):
|
||||||
|
attempts.append((device, compute_type))
|
||||||
|
return object()
|
||||||
|
|
||||||
|
def fake_run(wav, model, language, beam_size):
|
||||||
|
runs["n"] += 1
|
||||||
|
if runs["n"] == 1:
|
||||||
|
raise RuntimeError("CUDA failed with error out of memory")
|
||||||
|
return (
|
||||||
|
[cadence.Word("hi", 0.0, 1.0)],
|
||||||
|
[{"start": 0.0, "end": 1.0, "text": "hi"}],
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(cadence, "_load_faster_whisper_model", fake_load)
|
||||||
|
monkeypatch.setattr(cadence, "_run_faster_whisper", fake_run)
|
||||||
|
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: None)
|
||||||
|
|
||||||
|
words, raw_segments = cadence._transcribe_faster_whisper(Path("a.wav"), "large-v3")
|
||||||
|
|
||||||
|
assert words == [cadence.Word("hi", 0.0, 1.0)]
|
||||||
|
assert raw_segments == [{"start": 0.0, "end": 1.0, "text": "hi"}]
|
||||||
|
assert attempts == [("cuda", "int8_float16"), ("cuda", "int8")]
|
||||||
|
|
||||||
|
|
||||||
|
def test_transcribe_propagates_non_oom_errors(monkeypatch):
|
||||||
|
attempts: list[tuple[str, str]] = []
|
||||||
|
|
||||||
|
def fake_load(model_size, device=None, compute_type=None):
|
||||||
|
attempts.append((device, compute_type))
|
||||||
|
return object()
|
||||||
|
|
||||||
|
def fake_run(wav, model, language, beam_size):
|
||||||
|
raise RuntimeError("unrelated")
|
||||||
|
|
||||||
|
monkeypatch.setattr(cadence, "_load_faster_whisper_model", fake_load)
|
||||||
|
monkeypatch.setattr(cadence, "_run_faster_whisper", fake_run)
|
||||||
|
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
cadence._transcribe_faster_whisper(Path("a.wav"), "large-v3")
|
||||||
|
except RuntimeError as e:
|
||||||
|
assert "unrelated" in str(e)
|
||||||
|
else:
|
||||||
|
raise AssertionError("expected RuntimeError")
|
||||||
|
|
||||||
|
# A non-OOM error must not be swallowed into a second attempt.
|
||||||
|
assert len(attempts) == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_transcribe_raises_after_every_fallback_fails(monkeypatch):
|
||||||
|
attempts: list[tuple[str, str]] = []
|
||||||
|
|
||||||
|
def fake_load(model_size, device=None, compute_type=None):
|
||||||
|
attempts.append((device, compute_type))
|
||||||
|
return object()
|
||||||
|
|
||||||
|
def fake_run(wav, model, language, beam_size):
|
||||||
|
raise RuntimeError("CUDA failed with error out of memory")
|
||||||
|
|
||||||
|
monkeypatch.setattr(cadence, "_load_faster_whisper_model", fake_load)
|
||||||
|
monkeypatch.setattr(cadence, "_run_faster_whisper", fake_run)
|
||||||
|
monkeypatch.setattr(cadence, "_release_cuda_memory", lambda: None)
|
||||||
|
|
||||||
|
try:
|
||||||
|
cadence._transcribe_faster_whisper(Path("a.wav"), "large-v3")
|
||||||
|
except RuntimeError as e:
|
||||||
|
assert "fallback" in str(e)
|
||||||
|
else:
|
||||||
|
raise AssertionError("expected RuntimeError")
|
||||||
|
|
||||||
|
assert len(attempts) == len(cadence.FASTER_WHISPER_FALLBACKS)
|
||||||
Loading…
Reference in a new issue