chunks(): cut long audio at pauses (source 2e0cb98449a3)
Browse files- README.md +2 -1
- eg2_ko_reader.py +47 -7
README.md
CHANGED
|
@@ -39,7 +39,8 @@ stt = load() # load(device="cuda") on a GPU, load(device="mps") on a Mac
|
|
| 39 |
print(stt.transcribe("audio.wav")) # a file path, or stt.transcribe(array, sample_rate=44100)
|
| 40 |
```
|
| 41 |
|
| 42 |
-
* Any length.
|
|
|
|
| 43 |
* Any file libsndfile reads (wav, flac, ogg, mp3). It is converted to 16 kHz mono.
|
| 44 |
* The download is about 1.6 GB, of which the encoder is 1.49 GB.
|
| 45 |
|
|
|
|
| 39 |
print(stt.transcribe("audio.wav")) # a file path, or stt.transcribe(array, sample_rate=44100)
|
| 40 |
```
|
| 41 |
|
| 42 |
+
* Any length. `transcribe` cuts the audio into 30 s windows that overlap by 3.84 s and joins them.
|
| 43 |
+
* For long recordings, `stt.chunks("lecture.wav")` cuts the audio at pauses into pieces of at most 30 s and yields `{"start", "end", "text"}` for each, so you can show text as it comes. On a 55-minute lecture both ways gave the same accuracy.
|
| 44 |
* Any file libsndfile reads (wav, flac, ogg, mp3). It is converted to 16 kHz mono.
|
| 45 |
* The download is about 1.6 GB, of which the encoder is 1.49 GB.
|
| 46 |
|
eg2_ko_reader.py
CHANGED
|
@@ -89,6 +89,34 @@ def plan_windows(n_samples: int) -> list[Window]:
|
|
| 89 |
start_tok += step
|
| 90 |
|
| 91 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
# ----------------------------------------------------------------------------- reader
|
| 93 |
|
| 94 |
|
|
@@ -308,19 +336,31 @@ class Transcriber:
|
|
| 308 |
return np.zeros((0, len(self.vocab)), np.float32)
|
| 309 |
return np.concatenate(pieces)
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
| 313 |
if isinstance(audio, str | Path):
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
|
|
|
| 319 |
logits = self.logits(wav)
|
| 320 |
if logits.shape[0] == 0:
|
| 321 |
return ""
|
| 322 |
return self.vocab.decode(greedy_ctc(logits, self.vocab.blank_id))
|
| 323 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
def load(folder: str | Path | None = None, device: str | None = None) -> Transcriber:
|
| 326 |
"""Load the encoder and the reader from `folder` (default: the folder of this file).
|
|
|
|
| 89 |
start_tok += step
|
| 90 |
|
| 91 |
|
| 92 |
+
def split_on_pauses(
|
| 93 |
+
wav: np.ndarray, max_s: float = 30.0, search_s: float = 8.0
|
| 94 |
+
) -> list[tuple[int, int]]:
|
| 95 |
+
"""Cut long audio into chunks of at most `max_s` seconds, each cut at the quietest
|
| 96 |
+
100 ms in the last `search_s` seconds before the limit, so a cut falls in a pause rather
|
| 97 |
+
than inside a word. Returns (start, end) sample ranges that cover the audio end to end."""
|
| 98 |
+
n = len(wav)
|
| 99 |
+
limit = int(max_s * SAMPLE_RATE)
|
| 100 |
+
if n <= limit:
|
| 101 |
+
return [(0, n)] if n else []
|
| 102 |
+
hop = SAMPLE_RATE // 50 # 20 ms frames
|
| 103 |
+
frames = len(wav) // hop
|
| 104 |
+
energy = np.sqrt(
|
| 105 |
+
np.mean(wav[: frames * hop].reshape(frames, hop).astype(np.float64) ** 2, axis=1)
|
| 106 |
+
)
|
| 107 |
+
smooth = np.convolve(energy, np.ones(5) / 5, mode="same") # 100 ms
|
| 108 |
+
out, start = [], 0
|
| 109 |
+
while n - start > limit:
|
| 110 |
+
lo = (start + limit - int(search_s * SAMPLE_RATE)) // hop
|
| 111 |
+
hi = (start + limit) // hop
|
| 112 |
+
lo = max(lo, start // hop + 1)
|
| 113 |
+
cut = (lo + int(np.argmin(smooth[lo:hi]))) * hop + hop // 2 if hi > lo else start + limit
|
| 114 |
+
out.append((start, cut))
|
| 115 |
+
start = cut
|
| 116 |
+
out.append((start, n))
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
# ----------------------------------------------------------------------------- reader
|
| 121 |
|
| 122 |
|
|
|
|
| 336 |
return np.zeros((0, len(self.vocab)), np.float32)
|
| 337 |
return np.concatenate(pieces)
|
| 338 |
|
| 339 |
+
@staticmethod
|
| 340 |
+
def _wav(audio, sample_rate: int | None) -> np.ndarray:
|
| 341 |
if isinstance(audio, str | Path):
|
| 342 |
+
return load_audio(audio)
|
| 343 |
+
if sample_rate is None:
|
| 344 |
+
raise ValueError("pass sample_rate with an audio array")
|
| 345 |
+
return to_mono_16k(audio, sample_rate)
|
| 346 |
+
|
| 347 |
+
def _text(self, wav: np.ndarray) -> str:
|
| 348 |
logits = self.logits(wav)
|
| 349 |
if logits.shape[0] == 0:
|
| 350 |
return ""
|
| 351 |
return self.vocab.decode(greedy_ctc(logits, self.vocab.blank_id))
|
| 352 |
|
| 353 |
+
def transcribe(self, audio, sample_rate: int | None = None) -> str:
|
| 354 |
+
"""`audio` is a file path, or an array with its `sample_rate`."""
|
| 355 |
+
return self._text(self._wav(audio, sample_rate))
|
| 356 |
+
|
| 357 |
+
def chunks(self, audio, sample_rate: int | None = None, max_s: float = 30.0):
|
| 358 |
+
"""Transcribe long audio piece by piece, cut at pauses (`split_on_pauses`). Yields
|
| 359 |
+
{"start": s, "end": s, "text": ...} per chunk, so the text can be shown as it comes."""
|
| 360 |
+
wav = self._wav(audio, sample_rate)
|
| 361 |
+
for a, b in split_on_pauses(wav, max_s):
|
| 362 |
+
yield {"start": a / SAMPLE_RATE, "end": b / SAMPLE_RATE, "text": self._text(wav[a:b])}
|
| 363 |
+
|
| 364 |
|
| 365 |
def load(folder: str | Path | None = None, device: str | None = None) -> Transcriber:
|
| 366 |
"""Load the encoder and the reader from `folder` (default: the folder of this file).
|