diff --git a/src/clipwright/transcribe.py b/src/clipwright/transcribe.py index 189ace9..817b14c 100644 --- a/src/clipwright/transcribe.py +++ b/src/clipwright/transcribe.py @@ -10,6 +10,7 @@ from collections.abc import Callable from dataclasses import dataclass from pathlib import Path +from typing import Any import numpy as np import numpy.typing as npt @@ -98,8 +99,44 @@ def _offline() -> bool: return bool(constants.HF_HUB_OFFLINE) -def _run(audio: npt.NDArray[np.float32], model_size: str, device: str, language: str | None, - on_progress: Fraction | None = None, log: Callable[[str], None] = print) -> list[Word]: +# Long audio goes to whisper in windows of about this many seconds, so only one window's +# samples (10 min = 38 MB of float32) and whisper's features for it are in memory at a time. +WINDOW_SECONDS = 600.0 +# each cut is moved to the quietest hop within this many seconds of the planned point, +# so it falls between words instead of in the middle of one +CUT_SEARCH = 30.0 + +Reader = Callable[[float, float], npt.NDArray[np.float32]] + + +def plan_windows(db: npt.NDArray[np.float64], hop: float, duration: float, + length: float = WINDOW_SECONDS, search: float = CUT_SEARCH) -> list[tuple[float, float]]: + """Splits [0, duration] into back-to-back (start, end) windows of about `length` seconds. + + db is the loudness curve (one value per `hop`). Each cut goes to the middle of the quietest + hop within `search` seconds of where it would fall (on a tie, the one closest to that). A last + piece shorter than `search` is merged into the window before it, so there's never a tiny + window at the end.""" + if duration <= 0: + return [] + windows: list[tuple[float, float]] = [] + start = 0.0 + while duration - start > length + search: + target = start + length + lo = max(int((target - search) / hop), int(start / hop) + 1) + hi = min(int((target + search) / hop) + 1, len(db)) + if hi > lo: + quietest = lo + np.flatnonzero(db[lo:hi] == np.min(db[lo:hi])) + cut = (int(quietest[np.argmin(np.abs((quietest + 0.5) * hop - target))]) + 0.5) * hop + else: # the curve is shorter than the probed duration, cut on the plan + cut = target + windows.append((start, cut)) + start = cut + windows.append((start, duration)) + return windows + + +def _load(model_size: str, device: str, log: Callable[[str], None]) -> object: from faster_whisper import WhisperModel log(f"loading whisper {model_size} on {'the GPU' if device == 'cuda' else 'the CPU'}") @@ -107,17 +144,30 @@ def _run(audio: npt.NDArray[np.float32], model_size: str, device: str, language: t = time.perf_counter() # after a first-run download, so this is only the load model = WhisperModel(path, device=device, compute_type="float16" if device == "cuda" else "int8") log(f"whisper ready in {time.perf_counter() - t:.1f}s") - segments, _ = model.transcribe(audio, word_timestamps=True, vad_filter=True, language=language) + return model + + +def _run(read: Reader, windows: list[tuple[float, float]], model_size: str, device: str, + language: str | None, on_progress: Fraction | None = None, + log: Callable[[str], None] = print) -> list[Word]: + model: Any = _load(model_size, device, log) words: list[Word] = [] - duration = len(audio) / SAMPLE_RATE - # segments is a lazy generator, the actual GPU work happens while iterating - for seg in segments: - for w in seg.words or []: - text = w.word.strip() - if text: - words.append(Word(float(w.start), float(w.end), text)) - if on_progress and duration > 0: - on_progress(float(seg.end) / duration) + total = windows[-1][1] if windows else 0.0 + for start, end in windows: + audio = read(start, end - start) + segments, _ = model.transcribe(audio, word_timestamps=True, vad_filter=True, language=language) + del audio # whisper keeps its own features, the samples aren't needed while it runs + # segments is a lazy generator, the actual GPU work happens while iterating + for seg in segments: + for w in seg.words or []: + text = w.word.strip() + if text: + words.append(Word(start + float(w.start), start + float(w.end), text)) + if on_progress and total > 0: + on_progress((start + float(seg.end)) / total) + # a window with no speech yields no segments, so say it's done here + if on_progress and total > 0: + on_progress(end / total) return words @@ -146,7 +196,7 @@ def transcribe( log: Callable[[str], None] = print, on_progress: Fraction | None = None, ) -> list[Word]: - """audio: 16 kHz mono float32, the same buffer the loudness analysis already decoded. + """audio: 16 kHz mono float32, all of it in one call to whisper. Passing samples instead of a path skips faster-whisper's own PyAV decoding (a second full decode, and it breaks with some PyAV versions). @@ -156,17 +206,40 @@ def transcribe( on_progress gets the fraction of the audio transcribed so far, after each whisper segment. """ + return transcribe_windows(lambda _start, _duration: audio, [(0.0, len(audio) / SAMPLE_RATE)], + model_size, device, language, log, on_progress) + + +def transcribe_windows( + read: Reader, + windows: list[tuple[float, float]], + model_size: str = "small", + device: str = "auto", + language: str | None = None, + log: Callable[[str], None] = print, + on_progress: Fraction | None = None, +) -> list[Word]: + """Transcribes back-to-back windows (from plan_windows) one at a time with one loaded model. + + read(start, duration) returns that stretch as 16 kHz mono float32; it's called once per + window, right before whisper needs it, so only one window is in memory. Word times are on + the whole video's timeline. Whisper doesn't carry context across a cut, which is why the + cuts should be at quiet points. + + Same device fallback as transcribe(): a CUDA failure starts all windows over on the CPU.""" progress = monotonic(on_progress) + if not windows: + return [] if device == "cpu": - return _run(audio, model_size, "cpu", language, progress, log) + return _run(read, windows, model_size, "cpu", language, progress, log) _add_cuda_dll_dirs() try: - return _run(audio, model_size, "cuda", language, progress, log) + return _run(read, windows, model_size, "cuda", language, progress, log) except (RuntimeError, ValueError, OSError) as err: if device == "cuda" or not _is_cuda_error(err): raise log(f"GPU transcription unavailable ({err}), using CPU. `pip install clipwright[gpu]` fixes this.") - return _run(audio, model_size, "cpu", language, progress, log) + return _run(read, windows, model_size, "cpu", language, progress, log) def save_words(words: list[Word], path: Path) -> None: diff --git a/tests/test_whisper_windows.py b/tests/test_whisper_windows.py new file mode 100644 index 0000000..0c1d203 --- /dev/null +++ b/tests/test_whisper_windows.py @@ -0,0 +1,182 @@ +import sys +import types +from dataclasses import dataclass, field + +import numpy as np +import pytest + +from clipwright import transcribe +from clipwright.transcribe import Word, plan_windows + +SR = transcribe.SAMPLE_RATE + + +def test_short_audio_is_one_window(): + db = np.full(100, -20.0) + assert plan_windows(db, 0.5, 50.0) == [(0.0, 50.0)] + # up to length + search still fits in one window + assert plan_windows(np.full(1260, -20.0), 0.5, 630.0) == [(0.0, 630.0)] + + +def test_nothing_to_plan_for_no_audio(): + assert plan_windows(np.zeros(0), 0.5, 0.0) == [] + + +def test_cut_goes_to_the_quietest_point_near_the_plan(): + db = np.full(3000, -20.0) # 25 minutes at hop 0.5 + db[1180] = -45.0 # 590 s, inside 600 +- 30 + db[2500] = -60.0 # quieter, but 650 s past the first cut, out of the search range for the first one + windows = plan_windows(db, 0.5, 1500.0) + assert windows[0] == (0.0, 590.25) + assert windows[1][0] == 590.25 + # 590 + 600 = 1190 +- 30 is all -20, so the cut stays on the plan + assert windows[1][1] == 1190.25 + assert windows[2] == (1190.25, 1500.0) + + +def test_flat_curve_cuts_on_the_plan(): + assert plan_windows(np.full(3000, -20.0), 0.5, 1500.0) == [(0.0, 599.75), (599.75, 1199.75), (1199.75, 1500.0)] + + +def test_windows_are_back_to_back_and_cover_everything(): + rng = np.random.default_rng(1) + db = rng.uniform(-40, -10, 3 * 3600 * 2) + windows = plan_windows(db, 0.5, 3 * 3600.0) + assert windows[0][0] == 0.0 and windows[-1][1] == 3 * 3600.0 + assert all(a[1] == b[0] for a, b in zip(windows, windows[1:], strict=False)) + lengths = [b - a for a, b in windows] + assert all(570 <= n <= 630 for n in lengths[:-1]) + assert lengths[-1] <= 630 + 30 + + +def test_short_tail_is_merged_into_the_last_window(): + db = np.full(2500, -20.0) + db[1199] = -50.0 # cut at 599.75 + windows = plan_windows(db, 0.5, 1210.0) + # 1210 - 599.75 = 610 fits in one window, no 10 s piece at the end + assert windows == [(0.0, 599.75), (599.75, 1210.0)] + + +def test_curve_shorter_than_the_duration_cuts_on_the_plan(): + windows = plan_windows(np.full(10, -20.0), 0.5, 1500.0) + assert windows[0] == (0.0, 600.0) + assert windows[-1][1] == 1500.0 + + +@dataclass +class Fake: + """Records what the fake WhisperModel saw. Each call answers with one word 1 s into the + audio it was given, named after its length in seconds.""" + loads: list[str] = field(default_factory=list) + calls: list[tuple[str, int]] = field(default_factory=list) + fail_on_cuda: bool = False + + +def install(monkeypatch: pytest.MonkeyPatch) -> Fake: + fake = Fake() + + @dataclass + class W: + word: str + start: float + end: float + + @dataclass + class Seg: + end: float + words: list[W] + + class WhisperModel: + def __init__(self, path: str, device: str, compute_type: str) -> None: + self.device = device + fake.loads.append(device) + + def transcribe(self, audio: np.ndarray, **_kw: object): + fake.calls.append((self.device, len(audio))) + seconds = len(audio) / SR + + def segments(): + if fake.fail_on_cuda and self.device == "cuda": + raise RuntimeError("Library cublas64_12.dll is not found or cannot be loaded") + yield Seg(seconds, [W(f" {seconds:g}s", 1.0, 1.5)]) + + return segments(), None + + pkg = types.ModuleType("faster_whisper") + pkg.WhisperModel = WhisperModel # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "faster_whisper", pkg) + monkeypatch.setattr(transcribe, "_add_cuda_dll_dirs", lambda: None) + monkeypatch.setattr(transcribe, "ensure_model", lambda size, _log: size) + return fake + + +def reader(reads: list[tuple[float, float]]): + def read(start: float, duration: float) -> np.ndarray: + reads.append((start, duration)) + return np.zeros(int(duration * SR), dtype=np.float32) + return read + + +WINDOWS = [(0.0, 590.0), (590.0, 1200.0), (1200.0, 1500.0)] + + +def test_each_window_is_read_when_needed_and_words_are_on_the_video_timeline(monkeypatch: pytest.MonkeyPatch): + fake = install(monkeypatch) + reads: list[tuple[float, float]] = [] + seen: list[float] = [] + words = transcribe.transcribe_windows(reader(reads), WINDOWS, device="cuda", log=lambda _m: None, + on_progress=seen.append) + assert fake.loads == ["cuda"] # one model for all windows + assert reads == [(0.0, 590.0), (590.0, 610.0), (1200.0, 300.0)] + assert [c[1] for c in fake.calls] == [590 * SR, 610 * SR, 300 * SR] + assert words == [Word(1.0, 1.5, "590s"), Word(591.0, 591.5, "610s"), Word(1201.0, 1201.5, "300s")] + assert seen == pytest.approx([590 / 1500, 1200 / 1500, 1.0]) + + +def test_progress_moves_past_a_window_without_speech(monkeypatch: pytest.MonkeyPatch): + fake = install(monkeypatch) + seen: list[float] = [] + real_load = transcribe._load + + def load(size: str, device: str, log: object) -> object: + model = real_load(size, device, log) # type: ignore[arg-type] + answer = model.transcribe # type: ignore[attr-defined] + + def transcribe_(audio: np.ndarray, **kw: object): + if len(fake.calls) == 1: # the second window is all music, no segments + fake.calls.append(("quiet", len(audio))) + return iter(()), None + return answer(audio, **kw) + + model.transcribe = transcribe_ # type: ignore[attr-defined] + return model + + monkeypatch.setattr(transcribe, "_load", load) + transcribe.transcribe_windows(reader([]), WINDOWS, device="cpu", log=lambda _m: None, on_progress=seen.append) + assert seen == pytest.approx([590 / 1500, 1200 / 1500, 1.0]) + + +def test_cuda_failure_starts_every_window_over_on_the_cpu(monkeypatch: pytest.MonkeyPatch): + fake = install(monkeypatch) + fake.fail_on_cuda = True + reads: list[tuple[float, float]] = [] + logs: list[str] = [] + words = transcribe.transcribe_windows(reader(reads), WINDOWS, log=logs.append) + assert fake.loads == ["cuda", "cpu"] + assert [w.start for w in words] == [1.0, 591.0, 1201.0] # nothing from the failed attempt + assert reads[0] == (0.0, 590.0) and reads[1:] == [(0.0, 590.0), (590.0, 610.0), (1200.0, 300.0)] + assert any(m.startswith("GPU transcription unavailable") for m in logs) + + +def test_no_windows_loads_nothing(monkeypatch: pytest.MonkeyPatch): + fake = install(monkeypatch) + assert transcribe.transcribe_windows(reader([]), [], log=lambda _m: None) == [] + assert fake.loads == [] + + +def test_whole_array_is_still_one_call(monkeypatch: pytest.MonkeyPatch): + fake = install(monkeypatch) + audio = np.zeros(90 * SR, dtype=np.float32) + words = transcribe.transcribe(audio, device="cpu", log=lambda _m: None) + assert fake.calls == [("cpu", 90 * SR)] + assert words == [Word(1.0, 1.5, "90s")]