voxprep 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- voxprep/__init__.py +42 -0
- voxprep/_skill/SKILL.md +49 -0
- voxprep/agents.py +64 -0
- voxprep/backends/__init__.py +91 -0
- voxprep/backends/funasr.py +78 -0
- voxprep/backends/openai.py +135 -0
- voxprep/backends/parakeet.py +303 -0
- voxprep/backends/sensevoice.py +286 -0
- voxprep/chunker.py +421 -0
- voxprep/cli.py +469 -0
- voxprep/diagnose.py +130 -0
- voxprep/downloads.py +105 -0
- voxprep/fbank.py +155 -0
- voxprep/io.py +245 -0
- voxprep/mcp_server.py +214 -0
- voxprep/models/SILERO_VAD_LICENSE +21 -0
- voxprep/models/__init__.py +0 -0
- voxprep/models/silero_vad_16k_op15.onnx +0 -0
- voxprep/presets.py +208 -0
- voxprep/py.typed +0 -0
- voxprep/reference.py +220 -0
- voxprep/stitch.py +392 -0
- voxprep/transcript.py +408 -0
- voxprep/vad.py +190 -0
- voxprep-0.1.0.dist-info/METADATA +267 -0
- voxprep-0.1.0.dist-info/RECORD +29 -0
- voxprep-0.1.0.dist-info/WHEEL +4 -0
- voxprep-0.1.0.dist-info/entry_points.txt +2 -0
- voxprep-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Built-in local English model: NVIDIA Parakeet TDT 0.6B v2 as int8 ONNX, on onnxruntime.
|
|
2
|
+
|
|
3
|
+
No API key, no PyTorch, nothing leaves the computer. The model (about 660 MB) is downloaded
|
|
4
|
+
once on first use. English only; for Mandarin, Cantonese, Japanese or Korean voxprep uses
|
|
5
|
+
SenseVoice instead (``--language zh`` etc.), and for anything else Groq or OpenAI.
|
|
6
|
+
|
|
7
|
+
Parakeet-TDT-0.6B-v2 is by NVIDIA under CC BY 4.0. The ONNX export and int8 quantisation are
|
|
8
|
+
by k2-fsa/sherpa-onnx; the decoding loop follows sherpa-onnx's TDT greedy search. NVIDIA does
|
|
9
|
+
not endorse voxprep.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import time
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from .. import downloads
|
|
21
|
+
from ..chunker import Chunk
|
|
22
|
+
from ..fbank import nemo_mel
|
|
23
|
+
from .sensevoice import GROQ_TIP, _print_progress, _say
|
|
24
|
+
|
|
25
|
+
FOLDER = "parakeet-tdt-0.6b-v2-int8"
|
|
26
|
+
FRAME = 0.08 # seconds per encoder frame: 10 ms hop x subsampling 8
|
|
27
|
+
MAX_PER_FRAME = 5 # tokens emitted from one frame before moving on
|
|
28
|
+
SENTENCE_END = tuple(".?!")
|
|
29
|
+
PAUSE = 0.6 # seconds between words that end a segment without punctuation
|
|
30
|
+
# Mean token probability over the whole recording below which it is probably not English.
|
|
31
|
+
# QA: English 0.89-0.99 (0 dB café noise and a meeting at the low end); Spanish 0.75, French
|
|
32
|
+
# 0.67, Japanese 0.64, German 0.63, Mandarin 0.47.
|
|
33
|
+
LOW_CONFIDENCE = 0.82
|
|
34
|
+
# Unless told the language is English, it stops after the first EARLY_SECONDS of detected
|
|
35
|
+
# speech if under EARLY_WORDS of that speech came back with words, or their confidence averages
|
|
36
|
+
# under EARLY_STOP. First minute in QA: English (noise, music, meetings, phone, 8 kHz) >= 0.80
|
|
37
|
+
# with words and >= 0.86 confidence; Mandarin and Cantonese <= 0.38 with words (mostly none);
|
|
38
|
+
# German 0.62, French 0.65, Japanese 0.65, Mandarin-English mix 0.70, Spanish 0.77 (gets the
|
|
39
|
+
# end-of-run hint instead). Saves running a whole file into gibberish.
|
|
40
|
+
EARLY_SECONDS = 60.0
|
|
41
|
+
EARLY_WORDS = 0.5
|
|
42
|
+
EARLY_STOP = 0.75
|
|
43
|
+
|
|
44
|
+
ATTRIBUTION = (
|
|
45
|
+
"Parakeet-TDT-0.6B-v2 by NVIDIA, CC BY 4.0 "
|
|
46
|
+
"(https://huggingface.co/nvidia/parakeet-tdt-0.6b-v2); ONNX export and int8 "
|
|
47
|
+
"quantisation by k2-fsa/sherpa-onnx; NVIDIA does not endorse voxprep"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
_HF = "csukuangfj/sherpa-onnx-nemo-parakeet-tdt-0.6b-v2-int8"
|
|
51
|
+
_REV = "84b478d541cdbf0c296a7ab5f1e20a6f8f998114"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _urls(name: str) -> list[str]:
|
|
55
|
+
hf = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")
|
|
56
|
+
return [
|
|
57
|
+
f"{hf}/{_HF}/resolve/{_REV}/{name}",
|
|
58
|
+
f"https://hf-mirror.com/{_HF}/resolve/{_REV}/{name}",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
FILES = [
|
|
63
|
+
downloads.ModelFile(
|
|
64
|
+
"encoder.int8.onnx",
|
|
65
|
+
"92a10bd9c23936ea0566c29f963bc57c2a5df4261b6a8921c39abea66557ca8b",
|
|
66
|
+
652_282_309,
|
|
67
|
+
_urls("encoder.int8.onnx"),
|
|
68
|
+
),
|
|
69
|
+
downloads.ModelFile(
|
|
70
|
+
"decoder.int8.onnx",
|
|
71
|
+
"4d097bae3bac5c96018d5293ba39f1b657296102b142affda40378f38b020f41",
|
|
72
|
+
7_257_753,
|
|
73
|
+
_urls("decoder.int8.onnx"),
|
|
74
|
+
),
|
|
75
|
+
downloads.ModelFile(
|
|
76
|
+
"joiner.int8.onnx",
|
|
77
|
+
"77a29f3e5ac7d37074e0af465391b80f314015d5b97f0f90c6c7767f1d56f428",
|
|
78
|
+
1_739_080,
|
|
79
|
+
_urls("joiner.int8.onnx"),
|
|
80
|
+
),
|
|
81
|
+
downloads.ModelFile(
|
|
82
|
+
"tokens.txt",
|
|
83
|
+
"ec182b70dd42113aff6c5372c75cac58c952443eb22322f57bbd7f53977d497d",
|
|
84
|
+
9_384,
|
|
85
|
+
_urls("tokens.txt"),
|
|
86
|
+
),
|
|
87
|
+
]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def download(on_progress: Callable[[str, int, int], None] | None = _print_progress):
|
|
91
|
+
"""Fetch the model into the cache if it isn't there yet. Returns ``(folder, downloaded)``."""
|
|
92
|
+
if downloads.is_cached(FOLDER, FILES):
|
|
93
|
+
return downloads.cache_dir() / FOLDER, False
|
|
94
|
+
where = downloads.cache_dir()
|
|
95
|
+
_say(f"voxprep: downloading the local English speech model (about 660 MB, once) to {where}")
|
|
96
|
+
_say(f" {ATTRIBUTION}")
|
|
97
|
+
_say(f" For faster transcription, {GROQ_TIP}.")
|
|
98
|
+
return downloads.fetch(FOLDER, FILES, on_progress), True
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class NotEnglish(ValueError):
|
|
102
|
+
"""The recording doesn't sound like English; raised early instead of transcribing it all."""
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class ParakeetBackend:
|
|
106
|
+
name = "local"
|
|
107
|
+
preset = "parakeet"
|
|
108
|
+
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
language: str = "auto",
|
|
112
|
+
threads: int | None = None,
|
|
113
|
+
on_download: Callable[[str, int, int], None] | None = _print_progress,
|
|
114
|
+
sessions=None,
|
|
115
|
+
tokens: list[str] | None = None,
|
|
116
|
+
):
|
|
117
|
+
if language not in ("en", "auto"):
|
|
118
|
+
raise ValueError(
|
|
119
|
+
f"the local models know en, zh, yue, ja and ko, not {language!r}; "
|
|
120
|
+
f"for other languages {GROQ_TIP} and use --via groq"
|
|
121
|
+
)
|
|
122
|
+
self.language = "en"
|
|
123
|
+
self.told_english = language == "en"
|
|
124
|
+
self.downloaded = False
|
|
125
|
+
if sessions is None:
|
|
126
|
+
import onnxruntime as ort
|
|
127
|
+
|
|
128
|
+
folder, self.downloaded = download(on_download)
|
|
129
|
+
opts = ort.SessionOptions()
|
|
130
|
+
if threads:
|
|
131
|
+
opts.intra_op_num_threads = threads
|
|
132
|
+
cpu = ["CPUExecutionProvider"]
|
|
133
|
+
sessions = tuple(
|
|
134
|
+
ort.InferenceSession(str(folder / f"{part}.int8.onnx"), opts, providers=cpu)
|
|
135
|
+
for part in ("encoder", "decoder", "joiner")
|
|
136
|
+
)
|
|
137
|
+
tokens = _read_tokens(folder / "tokens.txt")
|
|
138
|
+
self.encoder, self.decoder, self.joiner = sessions
|
|
139
|
+
self.tokens = tokens or []
|
|
140
|
+
self.blank = len(self.tokens) - 1
|
|
141
|
+
meta = self.encoder.get_modelmeta().custom_metadata_map
|
|
142
|
+
self.layers = int(meta.get("pred_rnn_layers", 2))
|
|
143
|
+
self.hidden = int(meta.get("pred_hidden", 640))
|
|
144
|
+
self.feat_dim = int(meta.get("feat_dim", 128))
|
|
145
|
+
self.confidence: list[tuple[float, float]] = []
|
|
146
|
+
self.audio_seconds = 0.0
|
|
147
|
+
self.busy_seconds = 0.0
|
|
148
|
+
self.speech_seconds = 0.0 # detected speech sent so far
|
|
149
|
+
self.speech_with_words = 0.0 # ... in chunks that came back with any words
|
|
150
|
+
|
|
151
|
+
# ---------- one chunk ----------
|
|
152
|
+
|
|
153
|
+
def transcribe(self, chunk: Chunk, prompt: str | None = None) -> dict:
|
|
154
|
+
samples = chunk.audio.resample(16000).samples if chunk.audio is not None else _load(chunk)
|
|
155
|
+
began = time.perf_counter()
|
|
156
|
+
out = self.recognize(samples)
|
|
157
|
+
self.busy_seconds += time.perf_counter() - began
|
|
158
|
+
duration = len(samples) / 16000
|
|
159
|
+
self.audio_seconds += duration
|
|
160
|
+
speech = sum(sp.end - sp.start for sp in chunk.speech) if chunk.speech else duration
|
|
161
|
+
heard = self.speech_seconds
|
|
162
|
+
self.speech_seconds += speech
|
|
163
|
+
if out["segments"]:
|
|
164
|
+
self.confidence.append((out["confidence"], duration))
|
|
165
|
+
self.speech_with_words += speech
|
|
166
|
+
del out["confidence"]
|
|
167
|
+
if not self.told_english and heard < EARLY_SECONDS <= self.speech_seconds:
|
|
168
|
+
self._stop_if_foreign()
|
|
169
|
+
return out
|
|
170
|
+
|
|
171
|
+
def _stop_if_foreign(self) -> None:
|
|
172
|
+
"""Called once, after the first ``EARLY_SECONDS`` of detected speech."""
|
|
173
|
+
wordless = self.speech_with_words < EARLY_WORDS * self.speech_seconds
|
|
174
|
+
if wordless or self._mean() < EARLY_STOP:
|
|
175
|
+
raise NotEnglish(
|
|
176
|
+
"this doesn't sound like English, so the local English model stopped after "
|
|
177
|
+
f"the first {self.audio_seconds:.0f} s. For Mandarin, Cantonese, Japanese or "
|
|
178
|
+
"Korean, run again with --language zh (or yue, ja, ko). For other languages, "
|
|
179
|
+
f"{GROQ_TIP} and use --via groq. If it is English, add --language en to go on."
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
def recognize(self, samples: np.ndarray) -> dict:
|
|
183
|
+
feats, valid = nemo_mel(samples, num_bins=self.feat_dim)
|
|
184
|
+
enc, enc_len = self.encoder.run(
|
|
185
|
+
None, {"audio_signal": feats[None], "length": np.array([valid], dtype=np.int64)}
|
|
186
|
+
)
|
|
187
|
+
picked = self._greedy(enc, int(enc_len[0]))
|
|
188
|
+
return {**self._segments(picked), "language": "en"}
|
|
189
|
+
|
|
190
|
+
def _decoder_step(self, token: int, state):
|
|
191
|
+
names = [i.name for i in self.decoder.get_inputs()]
|
|
192
|
+
feeds = dict(
|
|
193
|
+
zip(
|
|
194
|
+
names,
|
|
195
|
+
[
|
|
196
|
+
np.array([[token]], dtype=np.int32),
|
|
197
|
+
np.array([1], dtype=np.int32),
|
|
198
|
+
*state,
|
|
199
|
+
],
|
|
200
|
+
strict=True,
|
|
201
|
+
)
|
|
202
|
+
)
|
|
203
|
+
out, _, *new_state = self.decoder.run(None, feeds)
|
|
204
|
+
return out, tuple(new_state)
|
|
205
|
+
|
|
206
|
+
def _greedy(self, enc: np.ndarray, frames: int) -> list[tuple[int, int, float]]:
|
|
207
|
+
"""TDT greedy search: ``(token, frame, probability)`` for each emitted token."""
|
|
208
|
+
zeros = np.zeros((self.layers, 1, self.hidden), dtype=np.float32)
|
|
209
|
+
state = (zeros, zeros.copy())
|
|
210
|
+
dec_out, next_state = self._decoder_step(self.blank, state)
|
|
211
|
+
enc_name, dec_name = (i.name for i in self.joiner.get_inputs())
|
|
212
|
+
vocab = len(self.tokens)
|
|
213
|
+
picked: list[tuple[int, int, float]] = []
|
|
214
|
+
t = emitted = 0
|
|
215
|
+
while t < frames:
|
|
216
|
+
logits = self.joiner.run(None, {enc_name: enc[:, :, t : t + 1], dec_name: dec_out})[
|
|
217
|
+
0
|
|
218
|
+
].reshape(-1)
|
|
219
|
+
tok_logits = logits[:vocab]
|
|
220
|
+
token = int(tok_logits.argmax())
|
|
221
|
+
skip = int(logits[vocab:].argmax())
|
|
222
|
+
if token != self.blank:
|
|
223
|
+
z = tok_logits - tok_logits[token]
|
|
224
|
+
picked.append((token, t, float(1.0 / np.exp(z).sum())))
|
|
225
|
+
state = next_state
|
|
226
|
+
dec_out, next_state = self._decoder_step(token, state)
|
|
227
|
+
emitted += 1
|
|
228
|
+
if skip == 0 and (token == self.blank or emitted >= MAX_PER_FRAME):
|
|
229
|
+
skip = 1
|
|
230
|
+
if skip:
|
|
231
|
+
emitted = 0
|
|
232
|
+
t += skip
|
|
233
|
+
return picked
|
|
234
|
+
|
|
235
|
+
def _segments(self, picked: list[tuple[int, int, float]]) -> dict:
|
|
236
|
+
segments, words, start, last = [], [], None, 0
|
|
237
|
+
|
|
238
|
+
def close():
|
|
239
|
+
text = "".join(words).replace("▁", " ").strip()
|
|
240
|
+
if text:
|
|
241
|
+
segments.append({"start": start, "end": (last + 1) * FRAME, "text": text})
|
|
242
|
+
|
|
243
|
+
for tok, t, _ in picked:
|
|
244
|
+
piece = self.tokens[tok]
|
|
245
|
+
if words and piece.startswith("▁") and (t - last) * FRAME >= PAUSE:
|
|
246
|
+
close()
|
|
247
|
+
words, start = [], None
|
|
248
|
+
if start is None:
|
|
249
|
+
start = t * FRAME
|
|
250
|
+
words.append(piece)
|
|
251
|
+
last = t
|
|
252
|
+
if piece.endswith(SENTENCE_END):
|
|
253
|
+
close()
|
|
254
|
+
words, start = [], None
|
|
255
|
+
close()
|
|
256
|
+
conf = float(np.mean([p for *_, p in picked])) if picked else 0.0
|
|
257
|
+
return {"segments": segments, "confidence": conf}
|
|
258
|
+
|
|
259
|
+
# ---------- advice for the user ----------
|
|
260
|
+
|
|
261
|
+
@property
|
|
262
|
+
def unsure(self) -> bool:
|
|
263
|
+
return self._mean() < LOW_CONFIDENCE
|
|
264
|
+
|
|
265
|
+
def _mean(self) -> float:
|
|
266
|
+
"""Token confidence averaged over the speech heard so far (1.0 before any)."""
|
|
267
|
+
total = sum(d for _, d in self.confidence)
|
|
268
|
+
return sum(c * d for c, d in self.confidence) / total if total > 0 else 1.0
|
|
269
|
+
|
|
270
|
+
@property
|
|
271
|
+
def speed(self) -> float | None:
|
|
272
|
+
return self.audio_seconds / self.busy_seconds if self.busy_seconds > 0.5 else None
|
|
273
|
+
|
|
274
|
+
@property
|
|
275
|
+
def hint(self) -> str | None:
|
|
276
|
+
if self.unsure:
|
|
277
|
+
return (
|
|
278
|
+
"The local model only knows English and wasn't sure about this recording. "
|
|
279
|
+
"For Mandarin, Cantonese, Japanese or Korean, run again with --language zh "
|
|
280
|
+
f"(or yue, ja, ko). For other languages, {GROQ_TIP} and use --via groq."
|
|
281
|
+
)
|
|
282
|
+
if self.busy_seconds > 300:
|
|
283
|
+
return (
|
|
284
|
+
f"That took {self.busy_seconds / 60:.0f} min on this computer; Groq usually "
|
|
285
|
+
f"takes about a minute per hour of audio. To use it, {GROQ_TIP}."
|
|
286
|
+
)
|
|
287
|
+
if self.downloaded:
|
|
288
|
+
return (
|
|
289
|
+
"Used the built-in local model (downloaded once, now cached). "
|
|
290
|
+
f"For faster transcription, {GROQ_TIP}."
|
|
291
|
+
)
|
|
292
|
+
return None
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _read_tokens(path) -> list[str]:
|
|
296
|
+
with open(path, encoding="utf-8") as f:
|
|
297
|
+
return [line.rstrip("\n").rsplit(" ", 1)[0] for line in f]
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _load(chunk) -> np.ndarray:
|
|
301
|
+
from ..io import load
|
|
302
|
+
|
|
303
|
+
return load(chunk.path, 16000).samples
|
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
"""Built-in local model for Mandarin, Cantonese, Japanese and Korean: SenseVoiceSmall as ONNX.
|
|
2
|
+
|
|
3
|
+
Used when the language is given as zh, yue, ja or ko (English goes to Parakeet). No API key,
|
|
4
|
+
no PyTorch, nothing leaves the computer. The model (about 240 MB) is downloaded once, on
|
|
5
|
+
first use; see :mod:`voxprep.downloads` for where it goes.
|
|
6
|
+
|
|
7
|
+
SenseVoiceSmall is by Alibaba's FunAudioLLM team and is under the FunASR Model Open Source
|
|
8
|
+
License Agreement v1.1, not voxprep's MIT license. The ONNX export is by k2-fsa/sherpa-onnx;
|
|
9
|
+
the feature pipeline here follows its SenseVoice reference script.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
from collections import Counter
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
from .. import downloads
|
|
23
|
+
from ..chunker import Chunk
|
|
24
|
+
from ..fbank import fbank
|
|
25
|
+
|
|
26
|
+
LANGUAGES = ("zh", "en", "yue", "ja", "ko")
|
|
27
|
+
FOLDER = "sensevoice-small-int8"
|
|
28
|
+
FRAME = 0.06 # seconds per output frame: 10 ms shift x LFR shift 6
|
|
29
|
+
SENTENCE_END = tuple("。!?!?.")
|
|
30
|
+
PAUSE = 0.6 # seconds between tokens that end a sentence without punctuation
|
|
31
|
+
|
|
32
|
+
ATTRIBUTION = (
|
|
33
|
+
"SenseVoiceSmall by FunAudioLLM / Alibaba Group, under the FunASR Model Open Source "
|
|
34
|
+
"License Agreement v1.1 (https://github.com/modelscope/FunASR/blob/main/MODEL_LICENSE); "
|
|
35
|
+
"ONNX export by k2-fsa/sherpa-onnx"
|
|
36
|
+
)
|
|
37
|
+
GROQ_TIP = "set GROQ_API_KEY (free key: https://console.groq.com/keys)"
|
|
38
|
+
|
|
39
|
+
_HF = "csukuangfj/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17"
|
|
40
|
+
_HF_REV = "2365baeacb507f821a0c8120fcee3d484dba7a07"
|
|
41
|
+
_MS = "pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue"
|
|
42
|
+
_MS_REV = "73eca47697f980daa3d16112404174b6b950b514"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _urls(name: str) -> list[str]:
|
|
46
|
+
hf = os.environ.get("HF_ENDPOINT", "https://huggingface.co").rstrip("/")
|
|
47
|
+
urls = [
|
|
48
|
+
f"{hf}/{_HF}/resolve/{_HF_REV}/{name}",
|
|
49
|
+
f"https://www.modelscope.cn/models/{_MS}/resolve/{_MS_REV}/{name}",
|
|
50
|
+
f"https://hf-mirror.com/{_HF}/resolve/{_HF_REV}/{name}",
|
|
51
|
+
]
|
|
52
|
+
if os.environ.get("VOXPREP_MIRROR") == "modelscope":
|
|
53
|
+
urls.insert(0, urls.pop(1))
|
|
54
|
+
return urls
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
FILES = [
|
|
58
|
+
downloads.ModelFile(
|
|
59
|
+
"model.int8.onnx",
|
|
60
|
+
"c71f0ce00bec95b07744e116345e33d8cbbe08cef896382cf907bf4b51a2cd51",
|
|
61
|
+
239_233_841,
|
|
62
|
+
_urls("model.int8.onnx"),
|
|
63
|
+
),
|
|
64
|
+
downloads.ModelFile(
|
|
65
|
+
"tokens.txt",
|
|
66
|
+
"f449eb28dc567533d7fa59be34e2abca8784f771850c78a47fb731a31429a1dc",
|
|
67
|
+
315_894,
|
|
68
|
+
_urls("tokens.txt"),
|
|
69
|
+
),
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _say(msg: str) -> None:
|
|
74
|
+
print(msg, file=sys.stderr, flush=True)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _print_progress(name: str, done: int, total: int) -> None:
|
|
78
|
+
if name.endswith(".onnx"):
|
|
79
|
+
step = total // 20 or 1
|
|
80
|
+
if done == total or done // step != (done - (1 << 20)) // step:
|
|
81
|
+
_say(f" {name}: {done / 1e6:.0f}/{total / 1e6:.0f} MB")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def download(on_progress: Callable[[str, int, int], None] | None = _print_progress):
|
|
85
|
+
"""Fetch the model into the cache if it isn't there yet. Returns ``(folder, downloaded)``."""
|
|
86
|
+
if downloads.is_cached(FOLDER, FILES):
|
|
87
|
+
return downloads.cache_dir() / FOLDER, False
|
|
88
|
+
where = downloads.cache_dir()
|
|
89
|
+
_say(f"voxprep: downloading the local speech model (about 240 MB, once) to {where}")
|
|
90
|
+
_say(f" {ATTRIBUTION}")
|
|
91
|
+
_say(f" For faster transcription or other languages, {GROQ_TIP}.")
|
|
92
|
+
return downloads.fetch(FOLDER, FILES, on_progress), True
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class SenseVoiceBackend:
|
|
96
|
+
name = "local"
|
|
97
|
+
preset = "sensevoice"
|
|
98
|
+
|
|
99
|
+
def __init__(
|
|
100
|
+
self,
|
|
101
|
+
language: str = "auto",
|
|
102
|
+
use_itn: bool = True,
|
|
103
|
+
threads: int | None = None,
|
|
104
|
+
on_download: Callable[[str, int, int], None] | None = _print_progress,
|
|
105
|
+
session=None,
|
|
106
|
+
tokens: list[str] | None = None,
|
|
107
|
+
):
|
|
108
|
+
if language != "auto" and language not in LANGUAGES:
|
|
109
|
+
raise ValueError(
|
|
110
|
+
f"the local model knows {', '.join(LANGUAGES)}, not {language!r}; "
|
|
111
|
+
f"for other languages {GROQ_TIP} and use --via groq"
|
|
112
|
+
)
|
|
113
|
+
self.language = language
|
|
114
|
+
self.downloaded = False
|
|
115
|
+
if session is None:
|
|
116
|
+
import onnxruntime as ort
|
|
117
|
+
|
|
118
|
+
folder, self.downloaded = download(on_download)
|
|
119
|
+
opts = ort.SessionOptions()
|
|
120
|
+
if threads:
|
|
121
|
+
opts.intra_op_num_threads = threads
|
|
122
|
+
session = ort.InferenceSession(
|
|
123
|
+
str(folder / "model.int8.onnx"), opts, providers=["CPUExecutionProvider"]
|
|
124
|
+
)
|
|
125
|
+
tokens = _read_tokens(folder / "tokens.txt")
|
|
126
|
+
self.session = session
|
|
127
|
+
self.tokens = tokens or []
|
|
128
|
+
meta = session.get_modelmeta().custom_metadata_map
|
|
129
|
+
self.lfr = (int(meta.get("lfr_window_size", 7)), int(meta.get("lfr_window_shift", 6)))
|
|
130
|
+
self.neg_mean = np.array(meta["neg_mean"].split(","), dtype=np.float32)
|
|
131
|
+
self.inv_std = np.array(meta["inv_stddev"].split(","), dtype=np.float32)
|
|
132
|
+
self.scale = 1.0 if meta.get("normalize_samples", "0") == "1" else 32768.0
|
|
133
|
+
self.lang_ids = {k[5:]: int(v) for k, v in meta.items() if k.startswith("lang_")}
|
|
134
|
+
self.itn_id = int(meta["with_itn" if use_itn else "without_itn"])
|
|
135
|
+
self.detected: Counter[str] = Counter()
|
|
136
|
+
self.confidence: list[tuple[float, float]] = [] # (mean token prob, seconds) per chunk
|
|
137
|
+
self.audio_seconds = 0.0
|
|
138
|
+
self.busy_seconds = 0.0
|
|
139
|
+
|
|
140
|
+
# ---------- one chunk ----------
|
|
141
|
+
|
|
142
|
+
def transcribe(self, chunk: Chunk, prompt: str | None = None) -> dict:
|
|
143
|
+
samples = (
|
|
144
|
+
chunk.audio.resample(16000).samples if chunk.audio is not None else _load(chunk.path)
|
|
145
|
+
)
|
|
146
|
+
began = time.perf_counter()
|
|
147
|
+
feats = self.features(samples)
|
|
148
|
+
out = self._decode(feats, self.language)
|
|
149
|
+
if self.language == "auto":
|
|
150
|
+
# SenseVoice guesses the language per 28 s piece and sometimes guesses wrong,
|
|
151
|
+
# which garbles that piece; redo it in the language that clearly dominates.
|
|
152
|
+
main, n = self.detected.most_common(1)[0] if self.detected else (None, 0)
|
|
153
|
+
heard = out["language"]
|
|
154
|
+
if heard in LANGUAGES and main and heard != main and n >= 2:
|
|
155
|
+
if n >= 0.6 * self.detected.total():
|
|
156
|
+
out = self._decode(feats, main)
|
|
157
|
+
if out["language"] in LANGUAGES:
|
|
158
|
+
self.detected[out["language"]] += 1
|
|
159
|
+
self.busy_seconds += time.perf_counter() - began
|
|
160
|
+
duration = len(samples) / 16000
|
|
161
|
+
self.audio_seconds += duration
|
|
162
|
+
if out["segments"]:
|
|
163
|
+
self.confidence.append((out.pop("confidence"), duration))
|
|
164
|
+
else:
|
|
165
|
+
out.pop("confidence")
|
|
166
|
+
return out
|
|
167
|
+
|
|
168
|
+
def features(self, samples: np.ndarray) -> np.ndarray:
|
|
169
|
+
f = fbank(samples * self.scale, 16000, window="hamming", snip_edges=False)
|
|
170
|
+
size, shift = self.lfr
|
|
171
|
+
if len(f) < size: # very short input: repeat the last frame
|
|
172
|
+
f = np.concatenate(
|
|
173
|
+
[f, np.repeat(f[-1:] if len(f) else np.zeros((1, 80)), size - len(f), 0)]
|
|
174
|
+
)
|
|
175
|
+
t = (len(f) - size) // shift + 1
|
|
176
|
+
idx = np.arange(t)[:, None] * shift + np.arange(size)
|
|
177
|
+
stacked = f[idx].reshape(t, -1).astype(np.float32)
|
|
178
|
+
return (stacked + self.neg_mean) * self.inv_std
|
|
179
|
+
|
|
180
|
+
def _decode(self, feats: np.ndarray, language: str) -> dict:
|
|
181
|
+
logits = self.session.run(
|
|
182
|
+
["logits"],
|
|
183
|
+
{
|
|
184
|
+
"x": feats[None],
|
|
185
|
+
"x_length": np.array([len(feats)], dtype=np.int32),
|
|
186
|
+
"language": np.array([self.lang_ids.get(language, 0)], dtype=np.int32),
|
|
187
|
+
"text_norm": np.array([self.itn_id], dtype=np.int32),
|
|
188
|
+
},
|
|
189
|
+
)[0][0]
|
|
190
|
+
ids = logits.argmax(-1)
|
|
191
|
+
z = logits - logits.max(-1, keepdims=True)
|
|
192
|
+
probs = np.exp(z[np.arange(len(ids)), ids]) / np.exp(z).sum(-1)
|
|
193
|
+
|
|
194
|
+
picked: list[tuple[int, int, float]] = [] # (token, frame, prob)
|
|
195
|
+
prev = -1
|
|
196
|
+
for t, i in enumerate(ids):
|
|
197
|
+
if i != prev and i != 0:
|
|
198
|
+
picked.append((int(i), t, float(probs[t])))
|
|
199
|
+
prev = i
|
|
200
|
+
tags, body = picked[:4], picked[4:]
|
|
201
|
+
lang = self.tokens[tags[0][0]].strip("<|>") if tags else None
|
|
202
|
+
|
|
203
|
+
# A sentence ends at a full stop or, since Cantonese output often has none, at a pause
|
|
204
|
+
# between tokens; CTC puts each token at the moment it was said.
|
|
205
|
+
segments, words, start, last = [], [], None, 0
|
|
206
|
+
|
|
207
|
+
def close():
|
|
208
|
+
text = "".join(words).replace("▁", " ").strip()
|
|
209
|
+
if text:
|
|
210
|
+
segments.append({"start": start, "end": (last - 3) * FRAME, "text": text})
|
|
211
|
+
|
|
212
|
+
for tok, t, _ in body:
|
|
213
|
+
piece = self.tokens[tok]
|
|
214
|
+
if piece.startswith("<|"):
|
|
215
|
+
continue
|
|
216
|
+
if words and (t - last) * FRAME >= PAUSE:
|
|
217
|
+
close()
|
|
218
|
+
words, start = [], None
|
|
219
|
+
if start is None:
|
|
220
|
+
start = max(0.0, (t - 4) * FRAME)
|
|
221
|
+
words.append(piece)
|
|
222
|
+
last = t
|
|
223
|
+
if piece.endswith(SENTENCE_END):
|
|
224
|
+
close()
|
|
225
|
+
words, start = [], None
|
|
226
|
+
close()
|
|
227
|
+
conf = float(np.mean([p for *_, p in body])) if body else 0.0
|
|
228
|
+
return {"segments": segments, "language": lang, "confidence": conf}
|
|
229
|
+
|
|
230
|
+
# ---------- advice for the user ----------
|
|
231
|
+
|
|
232
|
+
@property
|
|
233
|
+
def unsure(self) -> bool:
|
|
234
|
+
"""Most of the speech came out with low confidence: likely a language it doesn't know."""
|
|
235
|
+
total = sum(d for _, d in self.confidence)
|
|
236
|
+
low = sum(d for c, d in self.confidence if c < LOW_CONFIDENCE)
|
|
237
|
+
return total > 0 and low / total > 0.5
|
|
238
|
+
|
|
239
|
+
@property
|
|
240
|
+
def speed(self) -> float | None:
|
|
241
|
+
"""Seconds of audio per second of work so far."""
|
|
242
|
+
return self.audio_seconds / self.busy_seconds if self.busy_seconds > 0.5 else None
|
|
243
|
+
|
|
244
|
+
@property
|
|
245
|
+
def hint(self) -> str | None:
|
|
246
|
+
if self.unsure:
|
|
247
|
+
return (
|
|
248
|
+
"The local model only knows Mandarin, English, Cantonese, Japanese and Korean, "
|
|
249
|
+
f"and wasn't sure about this recording. If it's another language, {GROQ_TIP} "
|
|
250
|
+
"and run it again with --via groq."
|
|
251
|
+
)
|
|
252
|
+
tips = []
|
|
253
|
+
main = self.language if self.language != "auto" else None
|
|
254
|
+
if main is None and self.detected:
|
|
255
|
+
main = self.detected.most_common(1)[0][0]
|
|
256
|
+
if main == "en":
|
|
257
|
+
tips.append(
|
|
258
|
+
"For English, Groq makes about half as many mistakes as the local model "
|
|
259
|
+
f"(roughly 5% vs 10% of words in our tests). To use it, {GROQ_TIP}."
|
|
260
|
+
)
|
|
261
|
+
if self.busy_seconds > SLOW_SECONDS:
|
|
262
|
+
tips.append(
|
|
263
|
+
f"That took {self.busy_seconds / 60:.0f} min on this computer; Groq usually "
|
|
264
|
+
f"takes about a minute per hour of audio. To use it, {GROQ_TIP}."
|
|
265
|
+
)
|
|
266
|
+
if not tips and self.downloaded:
|
|
267
|
+
tips.append(
|
|
268
|
+
"Used the built-in local model (downloaded once, now cached). "
|
|
269
|
+
f"For faster transcription, {GROQ_TIP}."
|
|
270
|
+
)
|
|
271
|
+
return " ".join(tips) or None
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
LOW_CONFIDENCE = 0.55 # mean token probability; calibrated on the QA set
|
|
275
|
+
SLOW_SECONDS = 300 # suggest Groq when a run took longer than this
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _read_tokens(path) -> list[str]:
|
|
279
|
+
with open(path, encoding="utf-8") as f:
|
|
280
|
+
return [line.rstrip("\n").rsplit(" ", 1)[0] for line in f]
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _load(path) -> np.ndarray:
|
|
284
|
+
from ..io import load
|
|
285
|
+
|
|
286
|
+
return load(path, 16000).samples
|