Repository navigation
Transcribe long audio in windows cut at quiet points #178
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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")] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Progress only moves when whisper yields a segment. With
vad_filter=Truea window with no speech (a 10 minute stretch of menu music or gameplay without talking is normal in a VOD) yields nothing, so the bar sits at the previous window's last segment for the whole window and then jumps. The old single call had the same gap, but now we know where each window ends, so reportingend / totalafter the loop oversegmentsis free and keeps the bar moving on long silent stretches.