diff --git a/src/clipwright/pipeline.py b/src/clipwright/pipeline.py index ce3a7c8..05ac41e 100644 --- a/src/clipwright/pipeline.py +++ b/src/clipwright/pipeline.py @@ -15,6 +15,7 @@ from typing import Any, Literal, NamedTuple import numpy as np +import numpy.typing as npt from . import ( aipick, @@ -96,8 +97,11 @@ def analyze(info: MediaInfo, job: Job, log: Log, db, silent = np.asarray(saved[0], dtype=np.float64), saved[1] else: log("reading audio") - # whisper needs the samples; otherwise only the loudness is kept, a chunk at a time - db, pcm = audio.read_loudness(info.path, job.hop, keep_samples=_will_transcribe(job, store), + # a short video's samples are kept for whisper, so they aren't decoded twice. A long one + # is decoded again a window at a time when whisper gets to it (_transcribe), so the + # whole track is never in memory. + keep = _will_transcribe(job, store) and info.duration <= transcribe.WINDOW_SECONDS + transcribe.CUT_SEARCH + db, pcm = audio.read_loudness(info.path, job.hop, keep_samples=keep, expected=info.duration, on_progress=lambda f: progress("audio", f)) silent = bool(len(db)) and float(np.max(db)) <= audio.SILENCE_DB + 1.0 if store: @@ -153,13 +157,9 @@ def analyze(info: MediaInfo, job: Job, log: Log, words = cached_words progress("transcribe", 1.0) elif transcribe.available(): - if pcm is None: # the loudness came from the cache, whisper still needs the samples - log("reading audio for whisper") - pcm = audio.decode_pcm(info.path, expected=info.duration) log(f"transcribing (whisper {job.whisper_model})") progress("transcribe", 0.0) - words = transcribe.transcribe(pcm, job.whisper_model, language=job.language, log=log, - on_progress=lambda f: progress("transcribe", f)) + words = _transcribe(info, job, db, pcm, log, progress) if store: # an empty transcript is kept too, a video with no speech shouldn't be transcribed every run store.put_words(job.whisper_model, job.language, words) @@ -189,6 +189,30 @@ def analyze(info: MediaInfo, job: Job, log: Log, return sig, words +def _transcribe(info: MediaInfo, job: Job, db: npt.NDArray[np.float64], pcm: npt.NDArray[np.float32] | None, + log: Log, progress: Progress) -> list[transcribe.Word]: + """Whisper on the kept samples when there are some, otherwise on windows of the track cut at + quiet points of the loudness curve, each decoded right before whisper needs it.""" + def on_progress(f: float) -> None: + progress("transcribe", f) + + if pcm is not None: + return transcribe.transcribe_windows(lambda _start, _duration: pcm, [(0.0, len(pcm) / audio.SAMPLE_RATE)], + job.whisper_model, language=job.language, log=log, + on_progress=on_progress) + # the curve covers the whole track, which can run past the container's duration + windows = transcribe.plan_windows(db, job.hop, max(info.duration, len(db) * job.hop), + transcribe.WINDOW_SECONDS, transcribe.CUT_SEARCH) + if len(windows) > 1: + log(f"transcribing in {len(windows)} parts of about {transcribe.WINDOW_SECONDS:.0f}s") + + def read(start: float, duration: float) -> npt.NDArray[np.float32]: + return audio.decode_pcm(info.path, start=start, duration=duration) + + return transcribe.transcribe_windows(read, windows, job.whisper_model, language=job.language, log=log, + on_progress=on_progress) + + def _will_transcribe(job: Job, store: cache.AnalysisCache | None) -> bool: """Whether analyze() will run whisper (if the track turns out not to be silent).""" if not job.captions or job.srt is not None or not transcribe.available(): diff --git a/src/clipwright/transcribe.py b/src/clipwright/transcribe.py index 817b14c..f5f9f13 100644 --- a/src/clipwright/transcribe.py +++ b/src/clipwright/transcribe.py @@ -99,12 +99,15 @@ def _offline() -> bool: return bool(constants.HF_HUB_OFFLINE) -# 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 +# Long audio goes to whisper in windows of about this many seconds, so only one window is in +# memory at a time. What decides the size is faster-whisper's feature extraction, which peaks at +# about 1 MB per second of audio it's given (587 MB for 10 minutes, 117 MB for 2; the samples +# themselves are 64 kB a second). Whisper reads 30 s at a time anyway, so a cut at a quiet point +# every 2 minutes costs little. +WINDOW_SECONDS = 120.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 +CUT_SEARCH = 20.0 Reader = Callable[[float, float], npt.NDArray[np.float32]] @@ -155,8 +158,9 @@ def _run(read: Reader, windows: list[tuple[float, float]], model_size: str, devi 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) + segments, info = 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 + before = len(words) # segments is a lazy generator, the actual GPU work happens while iterating for seg in segments: for w in seg.words or []: @@ -165,6 +169,11 @@ def _run(read: Reader, windows: list[tuple[float, float]], model_size: str, devi 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) + if language is None and len(words) > before and len(windows) > 1: + # whisper detects the language per call. Keep the one from the first window with speech + # for the rest: a window of music or a few shouted words is where it guesses wrong. + language = info.language + log(f"language: {language} (detected at {start:.0f}s, used for the rest)") # a window with no speech yields no segments, so say it's done here if on_progress and total > 0: on_progress(end / total) diff --git a/tests/test_cache_pipeline.py b/tests/test_cache_pipeline.py index bd148f9..c282232 100644 --- a/tests/test_cache_pipeline.py +++ b/tests/test_cache_pipeline.py @@ -142,16 +142,11 @@ def silence(*_a: object, **_k: object) -> np.ndarray: def test_whisper_still_gets_samples_when_loudness_is_cached(video: Path, fakes: Counts, monkeypatch: pytest.MonkeyPatch): analyze(video) # no captions: caches loudness only - heard: list[int] = [] - - def fake_transcribe(pcm: np.ndarray, *_a: object, **_k: object) -> list[transcribe.Word]: - heard.append(len(pcm)) - return [transcribe.Word(21.0, 21.4, "hello.")] - + fake = Whisper([transcribe.Word(21.0, 21.4, "hello.")]) monkeypatch.setattr(transcribe, "available", lambda: True) - monkeypatch.setattr(transcribe, "transcribe", fake_transcribe) + monkeypatch.setattr(transcribe, "transcribe_windows", fake) _sig, words = pipeline.analyze(info_for(video), pipeline.Job(source=video), log=lambda _m: None) - assert heard == [60 * audio.SAMPLE_RATE] and words + assert fake.heard == [60 * audio.SAMPLE_RATE] and words assert fakes.decodes == 2 @@ -173,10 +168,12 @@ class Whisper: def __init__(self, words: list[transcribe.Word]) -> None: self.words = words self.calls: list[tuple[str, str | None]] = [] + self.heard: list[int] = [] - def __call__(self, _pcm: np.ndarray, model: str, language: str | None = None, + def __call__(self, read: Any, windows: list[tuple[float, float]], model: str, language: str | None = None, **_k: object) -> list[transcribe.Word]: self.calls.append((model, language)) + self.heard = [len(read(a, b - a)) for a, b in windows] return list(self.words) @@ -184,7 +181,7 @@ def __call__(self, _pcm: np.ndarray, model: str, language: str | None = None, def whisper(monkeypatch: pytest.MonkeyPatch) -> Whisper: fake = Whisper([transcribe.Word(21.0, 21.4, "no"), transcribe.Word(21.4, 21.9, "way.")]) monkeypatch.setattr(transcribe, "available", lambda: True) - monkeypatch.setattr(transcribe, "transcribe", fake) + monkeypatch.setattr(transcribe, "transcribe_windows", fake) return fake @@ -229,7 +226,7 @@ def crash(*_a: object, **_k: object) -> list[transcribe.Word]: raise RuntimeError("CUDA out of memory") monkeypatch.setattr(transcribe, "available", lambda: True) - monkeypatch.setattr(transcribe, "transcribe", crash) + monkeypatch.setattr(transcribe, "transcribe_windows", crash) with pytest.raises(RuntimeError): captioned(video) saved = AnalysisCache(video) @@ -296,6 +293,47 @@ def spy(*a: Any, **k: Any) -> Any: assert kept == [False, True, True, False] +def test_short_video_gives_whisper_the_kept_samples(video: Path, fakes: Counts, whisper: Whisper): + captioned(video, cache=False) + assert whisper.heard == [60 * audio.SAMPLE_RATE] + assert fakes.decodes == 1 + + +def test_long_video_is_transcribed_a_window_at_a_time(video: Path, whisper: Whisper, + monkeypatch: pytest.MonkeyPatch): + """With 20 s windows the 60 s fake track is too long to keep, so each window is decoded on its + own with ffmpeg's -ss/-t, cut at the quiet points of the curve.""" + reads: list[tuple[float | None, float | None]] = [] + + def chunks(_path: Path, sample_rate: int, start: float | None, duration: float | None) -> Any: + reads.append((start, duration)) + t = np.arange(60 * sample_rate) / sample_rate + # loud, with a dip to silence at 19 s and 41 s for the cuts to find + x = np.where((np.abs(t - 19.25) < 0.25) | (np.abs(t - 41.25) < 0.25), 0.0, 0.5 * np.sin(2 * np.pi * 220 * t)) + a = int((start or 0.0) * sample_rate) + b = len(x) if duration is None else a + int(duration * sample_rate) + yield np.round(x[a:b] * 32767).astype(np.int16) + + kept: list[bool] = [] + real = audio.read_loudness + + def spy(*a: Any, **k: Any) -> Any: + kept.append(k["keep_samples"]) + return real(*a, **k) + + monkeypatch.setattr(audio, "_pcm_chunks", chunks) + monkeypatch.setattr(audio, "read_loudness", spy) + monkeypatch.setattr(scenes, "scan", lambda *_a, **_k: ([], Motion(5.0, np.zeros((300, 4), np.float32)))) + monkeypatch.setattr(transcribe, "WINDOW_SECONDS", 20.0) + monkeypatch.setattr(transcribe, "CUT_SEARCH", 5.0) + logs: list[str] = [] + pipeline.analyze(info_for(video), pipeline.Job(source=video, cache=False), log=logs.append) + assert kept == [False] + assert reads == [(None, None), (0.0, 19.25), (19.25, 22.0), (41.25, 18.75)] + assert whisper.heard == [19.25 * audio.SAMPLE_RATE, 22 * audio.SAMPLE_RATE, 18.75 * audio.SAMPLE_RATE] + assert "transcribing in 3 parts of about 20s" in logs + + def test_audio_stage_moves_while_decoding(video: Path, fakes: Counts): events: list[tuple[str, float]] = [] pipeline.analyze(info_for(video), pipeline.Job(source=video, captions=False), log=lambda _m: None, diff --git a/tests/test_whisper_windows.py b/tests/test_whisper_windows.py index 0c1d203..ab88f28 100644 --- a/tests/test_whisper_windows.py +++ b/tests/test_whisper_windows.py @@ -11,22 +11,36 @@ SR = transcribe.SAMPLE_RATE +def plan(db: np.ndarray, hop: float, duration: float) -> list[tuple[float, float]]: + """The planner with 10 minute windows and a 30 s search, which the numbers below are made for.""" + return plan_windows(db, hop, duration, 600.0, 30.0) + + +def test_default_windows_keep_whisper_features_small(): + # faster-whisper's feature extraction peaks at ~1 MB per second of audio it's given, so no + # window may be longer than about 140 s with the defaults + rng = np.random.default_rng(2) + windows = plan_windows(rng.uniform(-40, -10, 3 * 3600 * 2), 0.5, 3 * 3600.0) + assert max(b - a for a, b in windows) <= transcribe.WINDOW_SECONDS + transcribe.CUT_SEARCH <= 140 + assert len(windows) == pytest.approx(3 * 3600 / transcribe.WINDOW_SECONDS, abs=6) + + 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)] + assert plan(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)] + assert plan(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) == [] + assert plan(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) + windows = plan(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 @@ -35,13 +49,13 @@ def test_cut_goes_to_the_quietest_point_near_the_plan(): 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)] + assert plan(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) + windows = plan(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] @@ -52,13 +66,13 @@ def test_windows_are_back_to_back_and_cover_everything(): 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) + windows = plan(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) + windows = plan(np.full(10, -20.0), 0.5, 1500.0) assert windows[0] == (0.0, 600.0) assert windows[-1][1] == 1500.0 @@ -70,6 +84,9 @@ class Fake: loads: list[str] = field(default_factory=list) calls: list[tuple[str, int]] = field(default_factory=list) fail_on_cuda: bool = False + languages: list[str | None] = field(default_factory=list) # what each call was asked for + detects: list[str] = field(default_factory=list) # what each call detects, "en" when empty + silent: set[int] = field(default_factory=set) # calls (by number) that hear no speech def install(monkeypatch: pytest.MonkeyPatch) -> Fake: @@ -91,16 +108,20 @@ 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): + def transcribe(self, audio: np.ndarray, language: str | None = None, **_kw: object): + call = len(fake.calls) fake.calls.append((self.device, len(audio))) + fake.languages.append(language) 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)]) + if call not in fake.silent: + yield Seg(seconds, [W(f" {seconds:g}s", 1.0, 1.5)]) - return segments(), None + detected = language or (fake.detects[call] if call < len(fake.detects) else "en") + return segments(), types.SimpleNamespace(language=detected) pkg = types.ModuleType("faster_whisper") pkg.WhisperModel = WhisperModel # type: ignore[attr-defined] @@ -180,3 +201,31 @@ def test_whole_array_is_still_one_call(monkeypatch: pytest.MonkeyPatch): words = transcribe.transcribe(audio, device="cpu", log=lambda _m: None) assert fake.calls == [("cpu", 90 * SR)] assert words == [Word(1.0, 1.5, "90s")] + + +def test_language_from_the_first_window_with_speech_is_used_for_the_rest(monkeypatch: pytest.MonkeyPatch): + fake = install(monkeypatch) + fake.silent = {0} # intro music: nothing heard, and its guess ("cy") isn't kept + fake.detects = ["cy", "de", "en"] + logs: list[str] = [] + words = transcribe.transcribe_windows(reader([]), WINDOWS, device="cpu", log=logs.append) + assert fake.languages == [None, None, "de"] + assert "language: de (detected at 590s, used for the rest)" in logs + assert len(words) == 2 + + +def test_a_given_language_is_never_replaced(monkeypatch: pytest.MonkeyPatch): + fake = install(monkeypatch) + fake.detects = ["de", "de", "de"] + logs: list[str] = [] + transcribe.transcribe_windows(reader([]), WINDOWS, device="cpu", language="en", log=logs.append) + assert fake.languages == ["en", "en", "en"] + assert not any(m.startswith("language:") for m in logs) + + +def test_one_window_says_nothing_about_the_language(monkeypatch: pytest.MonkeyPatch): + fake = install(monkeypatch) + logs: list[str] = [] + transcribe.transcribe(np.zeros(90 * SR, dtype=np.float32), device="cpu", log=logs.append) + assert fake.languages == [None] + assert not any(m.startswith("language:") for m in logs)