voxprep 0.1.0.dev0__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.
Potentially problematic release.
This version of voxprep might be problematic. Click here for more details.
- voxprep/__init__.py +42 -0
- voxprep/backends/__init__.py +43 -0
- voxprep/backends/funasr.py +53 -0
- voxprep/backends/openai.py +84 -0
- voxprep/chunker.py +421 -0
- voxprep/cli.py +311 -0
- voxprep/diagnose.py +130 -0
- voxprep/io.py +226 -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 +196 -0
- voxprep/py.typed +0 -0
- voxprep/reference.py +220 -0
- voxprep/stitch.py +204 -0
- voxprep/transcript.py +294 -0
- voxprep/vad.py +186 -0
- voxprep-0.1.0.dev0.dist-info/METADATA +183 -0
- voxprep-0.1.0.dev0.dist-info/RECORD +22 -0
- voxprep-0.1.0.dev0.dist-info/WHEEL +4 -0
- voxprep-0.1.0.dev0.dist-info/entry_points.txt +2 -0
- voxprep-0.1.0.dev0.dist-info/licenses/LICENSE +21 -0
voxprep/transcript.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""One transcript format for every backend, plus subtitle / text / Claude exports.
|
|
2
|
+
|
|
3
|
+
Whatever produced the text (OpenAI, Groq, FunASR, your own model), it becomes a
|
|
4
|
+
:class:`Transcript` of timed :class:`Segment` objects on the original file's timeline.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import math
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import asdict, dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
_CJK = re.compile(r"[ -〿-ヿ㐀-䶿一-鿿가--]")
|
|
16
|
+
_SENTENCE_END = re.compile(r"(?<=[。!?!?;;])|(?<=[.…])(?=\s)")
|
|
17
|
+
_CLAUSE_END = re.compile(r"(?<=[,,、::])")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Segment:
|
|
22
|
+
start: float
|
|
23
|
+
end: float
|
|
24
|
+
text: str
|
|
25
|
+
speaker: str | None = None
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def duration(self) -> float:
|
|
29
|
+
return self.end - self.start
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class Transcript:
|
|
34
|
+
segments: list[Segment] = field(default_factory=list)
|
|
35
|
+
language: str | None = None
|
|
36
|
+
duration: float | None = None
|
|
37
|
+
|
|
38
|
+
# ---------- construction ----------
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def from_dict(cls, data: dict) -> Transcript:
|
|
42
|
+
segs = [
|
|
43
|
+
Segment(float(s["start"]), float(s["end"]), str(s["text"]), s.get("speaker"))
|
|
44
|
+
for s in data.get("segments", [])
|
|
45
|
+
]
|
|
46
|
+
return cls(segs, data.get("language"), data.get("duration"))
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def from_json(cls, path: str | Path) -> Transcript:
|
|
50
|
+
return cls.from_dict(json.loads(Path(path).read_text(encoding="utf-8")))
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def text(self) -> str:
|
|
54
|
+
return join_texts(s.text for s in self.segments)
|
|
55
|
+
|
|
56
|
+
# ---------- shaping ----------
|
|
57
|
+
|
|
58
|
+
def refine(
|
|
59
|
+
self, max_width: int = 84, max_seconds: float = 7.0, max_gap: float = 1.0
|
|
60
|
+
) -> Transcript:
|
|
61
|
+
"""Re-cut segments into readable cues.
|
|
62
|
+
|
|
63
|
+
Long segments are split at sentence (then clause) boundaries with times shared out
|
|
64
|
+
by text width; short neighbours are merged while the cue stays under ``max_width``
|
|
65
|
+
display columns (CJK counts 2) and ``max_seconds``, and the pause between them is
|
|
66
|
+
under ``max_gap``. Fixes both the giant blocks some APIs return and the fragments
|
|
67
|
+
some local models produce.
|
|
68
|
+
"""
|
|
69
|
+
pieces: list[Segment] = []
|
|
70
|
+
for seg in self.segments:
|
|
71
|
+
pieces.extend(_split_segment(seg, max_width))
|
|
72
|
+
|
|
73
|
+
cues: list[Segment] = []
|
|
74
|
+
for p in pieces:
|
|
75
|
+
if cues:
|
|
76
|
+
cur = cues[-1]
|
|
77
|
+
merged = join_texts([cur.text, p.text])
|
|
78
|
+
fits = (
|
|
79
|
+
p.speaker == cur.speaker
|
|
80
|
+
and p.start - cur.end <= max_gap
|
|
81
|
+
and width(merged) <= max_width
|
|
82
|
+
and p.end - cur.start <= max_seconds
|
|
83
|
+
)
|
|
84
|
+
sentence_done = _ends_sentence(cur.text) and width(cur.text) >= max_width * 0.5
|
|
85
|
+
if fits and not sentence_done:
|
|
86
|
+
cues[-1] = Segment(cur.start, p.end, merged, cur.speaker)
|
|
87
|
+
continue
|
|
88
|
+
cues.append(p)
|
|
89
|
+
return Transcript(cues, self.language, self.duration)
|
|
90
|
+
|
|
91
|
+
# ---------- exports ----------
|
|
92
|
+
|
|
93
|
+
def to_dict(self) -> dict:
|
|
94
|
+
return {
|
|
95
|
+
"language": self.language,
|
|
96
|
+
"duration": self.duration,
|
|
97
|
+
"text": self.text,
|
|
98
|
+
"segments": [asdict(s) for s in self.segments],
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
def to_json(self, path: str | Path | None = None) -> str:
|
|
102
|
+
out = json.dumps(self.to_dict(), ensure_ascii=False, indent=2)
|
|
103
|
+
return _write(path, out)
|
|
104
|
+
|
|
105
|
+
def to_srt(self, path: str | Path | None = None) -> str:
|
|
106
|
+
blocks = []
|
|
107
|
+
for i, s in enumerate(self.segments, 1):
|
|
108
|
+
text = f"{s.speaker}: {s.text}" if s.speaker else s.text
|
|
109
|
+
blocks.append(f"{i}\n{_ts(s.start, ',')} --> {_ts(s.end, ',')}\n{text.strip()}\n")
|
|
110
|
+
return _write(path, "\n".join(blocks))
|
|
111
|
+
|
|
112
|
+
def to_vtt(self, path: str | Path | None = None) -> str:
|
|
113
|
+
blocks = ["WEBVTT\n"]
|
|
114
|
+
for s in self.segments:
|
|
115
|
+
text = f"<v {s.speaker}>{s.text}" if s.speaker else s.text
|
|
116
|
+
blocks.append(f"{_ts(s.start, '.')} --> {_ts(s.end, '.')}\n{text.strip()}\n")
|
|
117
|
+
return _write(path, "\n".join(blocks))
|
|
118
|
+
|
|
119
|
+
def to_text(self, path: str | Path | None = None) -> str:
|
|
120
|
+
return _write(path, self.text + "\n")
|
|
121
|
+
|
|
122
|
+
def to_markdown(self, path: str | Path | None = None, title: str | None = None) -> str:
|
|
123
|
+
lines = [f"# {title}\n"] if title else []
|
|
124
|
+
for s in self.segments:
|
|
125
|
+
who = f"**{s.speaker}:** " if s.speaker else ""
|
|
126
|
+
lines.append(f"`{_clock(s.start)}` {who}{s.text.strip()} ")
|
|
127
|
+
return _write(path, "\n".join(lines) + "\n")
|
|
128
|
+
|
|
129
|
+
def save(self, path: str | Path, fmt: str | None = None) -> Path:
|
|
130
|
+
"""Write by extension: .srt .vtt .md .txt .json, or ``fmt='claude'``."""
|
|
131
|
+
path = Path(path)
|
|
132
|
+
fmt = fmt or path.suffix.lstrip(".").lower()
|
|
133
|
+
writers = {
|
|
134
|
+
"srt": self.to_srt,
|
|
135
|
+
"vtt": self.to_vtt,
|
|
136
|
+
"md": self.to_markdown,
|
|
137
|
+
"txt": self.to_text,
|
|
138
|
+
"json": self.to_json,
|
|
139
|
+
}
|
|
140
|
+
if fmt == "claude":
|
|
141
|
+
_write(path, json.dumps(self.to_claude(), ensure_ascii=False, indent=2))
|
|
142
|
+
elif fmt in writers:
|
|
143
|
+
writers[fmt](path)
|
|
144
|
+
else:
|
|
145
|
+
raise ValueError(f"unknown transcript format {fmt!r}")
|
|
146
|
+
return path
|
|
147
|
+
|
|
148
|
+
# ---------- Claude ----------
|
|
149
|
+
|
|
150
|
+
def claude_text(self) -> tuple[str, list[tuple[int, int, int]]]:
|
|
151
|
+
"""Timestamped plain text and ``(char_start, char_end, segment_index)`` per line."""
|
|
152
|
+
lines, spans, pos = [], [], 0
|
|
153
|
+
for i, s in enumerate(self.segments):
|
|
154
|
+
who = f"{s.speaker}: " if s.speaker else ""
|
|
155
|
+
line = f"[{_clock(s.start)}] {who}{s.text.strip()}"
|
|
156
|
+
lines.append(line)
|
|
157
|
+
spans.append((pos, pos + len(line), i))
|
|
158
|
+
pos += len(line) + 1 # newline
|
|
159
|
+
return "\n".join(lines), spans
|
|
160
|
+
|
|
161
|
+
def to_claude(self, title: str | None = None, citations: bool = True) -> dict:
|
|
162
|
+
"""A Claude Messages API ``document`` content block holding this transcript.
|
|
163
|
+
|
|
164
|
+
Claude can't take audio input, so this is how it "hears" a recording. With
|
|
165
|
+
citations on, pass each citation to :meth:`locate` to get the time in the recording.
|
|
166
|
+
"""
|
|
167
|
+
text, _ = self.claude_text()
|
|
168
|
+
block: dict = {
|
|
169
|
+
"type": "document",
|
|
170
|
+
"source": {"type": "text", "media_type": "text/plain", "data": text},
|
|
171
|
+
}
|
|
172
|
+
if title:
|
|
173
|
+
block["title"] = title
|
|
174
|
+
if citations:
|
|
175
|
+
block["citations"] = {"enabled": True}
|
|
176
|
+
return block
|
|
177
|
+
|
|
178
|
+
def locate(self, start_char, end_char: int | None = None) -> tuple[float, float] | None:
|
|
179
|
+
"""Map a character range of :meth:`claude_text` (or a Claude citation) to seconds.
|
|
180
|
+
|
|
181
|
+
``start_char`` may be a citation object or dict carrying ``start_char_index`` and
|
|
182
|
+
``end_char_index``.
|
|
183
|
+
"""
|
|
184
|
+
if end_char is None:
|
|
185
|
+
c = start_char
|
|
186
|
+
get = c.get if isinstance(c, dict) else lambda k: getattr(c, k, None)
|
|
187
|
+
start_char, end_char = get("start_char_index"), get("end_char_index")
|
|
188
|
+
if start_char is None or end_char is None:
|
|
189
|
+
return None
|
|
190
|
+
_, spans = self.claude_text()
|
|
191
|
+
hit = [self.segments[i] for a, b, i in spans if a < end_char and b > start_char]
|
|
192
|
+
if not hit:
|
|
193
|
+
return None
|
|
194
|
+
return hit[0].start, hit[-1].end
|
|
195
|
+
|
|
196
|
+
def estimate_tokens(self) -> int:
|
|
197
|
+
"""Rough LLM token count of :meth:`claude_text` (CJK ≈ 1 token/char, else ≈ 4 chars)."""
|
|
198
|
+
text, _ = self.claude_text()
|
|
199
|
+
cjk = len(_CJK.findall(text))
|
|
200
|
+
return math.ceil(cjk + (len(text) - cjk) / 4)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
# ---------- text helpers ----------
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def width(text: str) -> int:
|
|
207
|
+
"""Display width: CJK characters count 2."""
|
|
208
|
+
cjk = len(_CJK.findall(text))
|
|
209
|
+
return len(text) + cjk
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def join_texts(parts) -> str:
|
|
213
|
+
"""Join pieces with a space between Latin words and none around CJK."""
|
|
214
|
+
out = ""
|
|
215
|
+
for p in parts:
|
|
216
|
+
p = p.strip()
|
|
217
|
+
if not p:
|
|
218
|
+
continue
|
|
219
|
+
if out and not (_CJK.match(out[-1]) or _CJK.match(p[0])):
|
|
220
|
+
out += " "
|
|
221
|
+
out += p
|
|
222
|
+
return out
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def split_sentences(text: str) -> list[str]:
|
|
226
|
+
return [s.strip() for s in _SENTENCE_END.split(text) if s and s.strip()]
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _ends_sentence(text: str) -> bool:
|
|
230
|
+
return bool(text) and text.rstrip()[-1:] in "。!?!?.…;;"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _split_segment(seg: Segment, max_width: int) -> list[Segment]:
|
|
234
|
+
parts = split_sentences(seg.text)
|
|
235
|
+
final: list[str] = []
|
|
236
|
+
for p in parts:
|
|
237
|
+
if width(p) <= max_width:
|
|
238
|
+
final.append(p)
|
|
239
|
+
continue
|
|
240
|
+
clauses = [c.strip() for c in _CLAUSE_END.split(p) if c.strip()]
|
|
241
|
+
for c in clauses:
|
|
242
|
+
final.extend(_hard_wrap(c, max_width) if width(c) > max_width else [c])
|
|
243
|
+
if len(final) <= 1:
|
|
244
|
+
return [Segment(seg.start, seg.end, seg.text.strip(), seg.speaker)]
|
|
245
|
+
return [
|
|
246
|
+
Segment(a, b, t, seg.speaker)
|
|
247
|
+
for t, (a, b) in zip(final, share_time(final, seg.start, seg.end), strict=True)
|
|
248
|
+
]
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _hard_wrap(text: str, max_width: int) -> list[str]:
|
|
252
|
+
out, cur = [], ""
|
|
253
|
+
tokens = re.findall(r"[㐀-鿿-ヿ가-]|\S+\s*", text)
|
|
254
|
+
for tok in tokens:
|
|
255
|
+
if cur and width(cur + tok) > max_width:
|
|
256
|
+
out.append(cur.strip())
|
|
257
|
+
cur = ""
|
|
258
|
+
cur += tok
|
|
259
|
+
if cur.strip():
|
|
260
|
+
out.append(cur.strip())
|
|
261
|
+
return out
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def share_time(texts: list[str], start: float, end: float) -> list[tuple[float, float]]:
|
|
265
|
+
"""Split ``[start, end]`` among ``texts`` in proportion to their display width."""
|
|
266
|
+
weights = [max(1, width(t)) for t in texts]
|
|
267
|
+
total = sum(weights)
|
|
268
|
+
out, t = [], start
|
|
269
|
+
for w in weights:
|
|
270
|
+
d = (end - start) * w / total
|
|
271
|
+
out.append((round(t, 3), round(t + d, 3)))
|
|
272
|
+
t += d
|
|
273
|
+
return out
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _ts(seconds: float, sep: str) -> str:
|
|
277
|
+
ms = int(round(max(0.0, seconds) * 1000))
|
|
278
|
+
h, ms = divmod(ms, 3_600_000)
|
|
279
|
+
m, ms = divmod(ms, 60_000)
|
|
280
|
+
s, ms = divmod(ms, 1000)
|
|
281
|
+
return f"{h:02d}:{m:02d}:{s:02d}{sep}{ms:03d}"
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _clock(seconds: float) -> str:
|
|
285
|
+
s = int(max(0.0, seconds))
|
|
286
|
+
h, rem = divmod(s, 3600)
|
|
287
|
+
m, s = divmod(rem, 60)
|
|
288
|
+
return f"{h:02d}:{m:02d}:{s:02d}"
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _write(path: str | Path | None, text: str) -> str:
|
|
292
|
+
if path is not None:
|
|
293
|
+
Path(path).write_text(text, encoding="utf-8")
|
|
294
|
+
return text
|
voxprep/vad.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Voice activity detection without PyTorch.
|
|
2
|
+
|
|
3
|
+
Runs the bundled Silero VAD v6.3 ONNX model (MIT, ~1.25 MB) with onnxruntime, one
|
|
4
|
+
512-sample window at a time with the 64-sample context and recurrent state the model
|
|
5
|
+
expects. If onnxruntime is unavailable, falls back to a simple energy detector.
|
|
6
|
+
|
|
7
|
+
The probability-to-segment logic follows the reference ``get_speech_timestamps`` from
|
|
8
|
+
snakers4/silero-vad (MIT), reimplemented here in plain Python/numpy.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import math
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from importlib import resources
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from .io import Audio
|
|
21
|
+
|
|
22
|
+
SAMPLE_RATE = 16000
|
|
23
|
+
WINDOW = 512 # samples per model step at 16 kHz (32 ms)
|
|
24
|
+
CONTEXT = 64 # samples of the previous window prepended to each step
|
|
25
|
+
MODEL_FILE = "silero_vad_16k_op15.onnx"
|
|
26
|
+
MODEL_SHA256 = "59892301a48e373121ff29ef512598b4e5ff7ebba1a461e05d490fb3c21b354b"
|
|
27
|
+
FRAME_SEC = WINDOW / SAMPLE_RATE
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Span:
|
|
32
|
+
"""A time range in seconds."""
|
|
33
|
+
|
|
34
|
+
start: float
|
|
35
|
+
end: float
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def duration(self) -> float:
|
|
39
|
+
return self.end - self.start
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SileroVAD:
|
|
43
|
+
"""Frame-level speech probabilities from the Silero ONNX model."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, threads: int = 1, verify: bool = True):
|
|
46
|
+
import onnxruntime as ort
|
|
47
|
+
|
|
48
|
+
data = resources.files("voxprep.models").joinpath(MODEL_FILE).read_bytes()
|
|
49
|
+
if verify and hashlib.sha256(data).hexdigest() != MODEL_SHA256:
|
|
50
|
+
raise RuntimeError(f"{MODEL_FILE} checksum mismatch; reinstall voxprep")
|
|
51
|
+
opts = ort.SessionOptions()
|
|
52
|
+
opts.inter_op_num_threads = 1
|
|
53
|
+
opts.intra_op_num_threads = threads
|
|
54
|
+
self._session = ort.InferenceSession(data, opts, providers=["CPUExecutionProvider"])
|
|
55
|
+
self._sr = np.array(SAMPLE_RATE, dtype=np.int64)
|
|
56
|
+
|
|
57
|
+
def probabilities(self, samples: np.ndarray) -> np.ndarray:
|
|
58
|
+
"""Speech probability for each 32 ms window of 16 kHz mono float32 audio."""
|
|
59
|
+
n = math.ceil(len(samples) / WINDOW)
|
|
60
|
+
if n == 0:
|
|
61
|
+
return np.zeros(0, np.float32)
|
|
62
|
+
padded = np.zeros(n * WINDOW + CONTEXT, np.float32)
|
|
63
|
+
padded[CONTEXT : CONTEXT + len(samples)] = samples
|
|
64
|
+
state = np.zeros((2, 1, 128), np.float32)
|
|
65
|
+
probs = np.empty(n, np.float32)
|
|
66
|
+
run = self._session.run
|
|
67
|
+
for i in range(n):
|
|
68
|
+
x = padded[i * WINDOW : i * WINDOW + WINDOW + CONTEXT].reshape(1, -1)
|
|
69
|
+
out, state = run(None, {"input": x, "state": state, "sr": self._sr})
|
|
70
|
+
probs[i] = out[0, 0]
|
|
71
|
+
return probs
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def energy_probabilities(samples: np.ndarray) -> np.ndarray:
|
|
75
|
+
"""Fallback: map per-window RMS energy to a pseudo-probability (no ML runtime)."""
|
|
76
|
+
n = math.ceil(len(samples) / WINDOW)
|
|
77
|
+
if n == 0:
|
|
78
|
+
return np.zeros(0, np.float32)
|
|
79
|
+
padded = np.zeros(n * WINDOW, np.float32)
|
|
80
|
+
padded[: len(samples)] = samples
|
|
81
|
+
rms = np.sqrt(np.mean(padded.reshape(n, WINDOW) ** 2, axis=1) + 1e-12)
|
|
82
|
+
db = 20 * np.log10(rms)
|
|
83
|
+
live = db[db > -80] # ignore digital silence, which would drag the floor down
|
|
84
|
+
floor = float(np.percentile(live, 10)) if len(live) else -80.0
|
|
85
|
+
# 0 at the noise floor, 0.5 at +12 dB, 1 at +24 dB.
|
|
86
|
+
return np.clip((db - floor) / 24.0, 0.0, 1.0).astype(np.float32)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
_default_vad: SileroVAD | None = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def probabilities(audio: Audio, backend: str = "auto") -> np.ndarray:
|
|
93
|
+
"""Per-window speech probabilities; ``backend`` is ``auto``, ``silero`` or ``energy``."""
|
|
94
|
+
global _default_vad
|
|
95
|
+
samples = audio.resample(SAMPLE_RATE).samples
|
|
96
|
+
if backend == "energy":
|
|
97
|
+
return energy_probabilities(samples)
|
|
98
|
+
try:
|
|
99
|
+
if _default_vad is None:
|
|
100
|
+
_default_vad = SileroVAD()
|
|
101
|
+
return _default_vad.probabilities(samples)
|
|
102
|
+
except ImportError:
|
|
103
|
+
if backend == "silero":
|
|
104
|
+
raise
|
|
105
|
+
return energy_probabilities(samples)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def speech_spans(
|
|
109
|
+
probs: np.ndarray,
|
|
110
|
+
duration: float,
|
|
111
|
+
threshold: float = 0.5,
|
|
112
|
+
min_speech: float = 0.25,
|
|
113
|
+
min_silence: float = 0.1,
|
|
114
|
+
pad: float = 0.03,
|
|
115
|
+
max_speech: float = math.inf,
|
|
116
|
+
) -> list[Span]:
|
|
117
|
+
"""Turn window probabilities into speech spans (seconds), Silero-style.
|
|
118
|
+
|
|
119
|
+
Speech starts when probability reaches ``threshold`` and ends after ``min_silence``
|
|
120
|
+
seconds below ``threshold - 0.15``. Spans shorter than ``min_speech`` are dropped,
|
|
121
|
+
each span is padded by ``pad`` seconds, and spans longer than ``max_speech`` are
|
|
122
|
+
split at the last pause seen (or hard-cut if there was none).
|
|
123
|
+
"""
|
|
124
|
+
neg = max(threshold - 0.15, 0.01)
|
|
125
|
+
win = FRAME_SEC
|
|
126
|
+
max_len = max_speech - win - 2 * pad if math.isfinite(max_speech) else math.inf
|
|
127
|
+
pause_for_split = 0.098
|
|
128
|
+
|
|
129
|
+
spans: list[list[float]] = []
|
|
130
|
+
start: float | None = None
|
|
131
|
+
temp_end = prev_end = next_start = 0.0
|
|
132
|
+
|
|
133
|
+
for i, p in enumerate(probs):
|
|
134
|
+
t = i * win
|
|
135
|
+
if p >= threshold and temp_end:
|
|
136
|
+
temp_end = 0.0
|
|
137
|
+
if next_start < prev_end:
|
|
138
|
+
next_start = t
|
|
139
|
+
if p >= threshold and start is None:
|
|
140
|
+
start = t
|
|
141
|
+
continue
|
|
142
|
+
if start is not None and t - start > max_len:
|
|
143
|
+
if prev_end:
|
|
144
|
+
spans.append([start, prev_end])
|
|
145
|
+
start = None if next_start < prev_end else next_start
|
|
146
|
+
prev_end = next_start = temp_end = 0.0
|
|
147
|
+
else:
|
|
148
|
+
spans.append([start, t])
|
|
149
|
+
start = None
|
|
150
|
+
prev_end = next_start = temp_end = 0.0
|
|
151
|
+
continue
|
|
152
|
+
if p < neg and start is not None:
|
|
153
|
+
if not temp_end:
|
|
154
|
+
temp_end = t
|
|
155
|
+
if t - temp_end > pause_for_split:
|
|
156
|
+
prev_end = temp_end
|
|
157
|
+
if t - temp_end < min_silence:
|
|
158
|
+
continue
|
|
159
|
+
if temp_end - start > min_speech:
|
|
160
|
+
spans.append([start, temp_end])
|
|
161
|
+
start = None
|
|
162
|
+
prev_end = next_start = temp_end = 0.0
|
|
163
|
+
|
|
164
|
+
if start is not None and duration - start > min_speech:
|
|
165
|
+
spans.append([start, duration])
|
|
166
|
+
|
|
167
|
+
for i, s in enumerate(spans):
|
|
168
|
+
if i == 0:
|
|
169
|
+
s[0] = max(0.0, s[0] - pad)
|
|
170
|
+
if i < len(spans) - 1:
|
|
171
|
+
gap = spans[i + 1][0] - s[1]
|
|
172
|
+
if gap < 2 * pad:
|
|
173
|
+
s[1] += gap / 2
|
|
174
|
+
spans[i + 1][0] = max(0.0, spans[i + 1][0] - gap / 2)
|
|
175
|
+
else:
|
|
176
|
+
s[1] = min(duration, s[1] + pad)
|
|
177
|
+
spans[i + 1][0] = max(0.0, spans[i + 1][0] - pad)
|
|
178
|
+
else:
|
|
179
|
+
s[1] = min(duration, s[1] + pad)
|
|
180
|
+
|
|
181
|
+
return [Span(round(a, 3), round(b, 3)) for a, b in spans]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def detect(audio: Audio, backend: str = "auto", **kwargs) -> list[Span]:
|
|
185
|
+
"""Speech spans in ``audio`` (seconds). Keyword arguments go to :func:`speech_spans`."""
|
|
186
|
+
return speech_spans(probabilities(audio, backend), audio.duration, **kwargs)
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: voxprep
|
|
3
|
+
Version: 0.1.0.dev0
|
|
4
|
+
Summary: Get any audio or video into an AI model, and the results back on the original timeline. No PyTorch, no system FFmpeg.
|
|
5
|
+
Author: LL333111
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: asr,audio,chunking,llm,subtitles,transcription,vad,voice-clone,whisper
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
|
|
16
|
+
Requires-Python: >=3.12
|
|
17
|
+
Requires-Dist: av>=14.0
|
|
18
|
+
Requires-Dist: numpy>=1.26
|
|
19
|
+
Requires-Dist: onnxruntime>=1.20
|
|
20
|
+
Provides-Extra: funasr
|
|
21
|
+
Requires-Dist: funasr>=1.1; extra == 'funasr'
|
|
22
|
+
Provides-Extra: groq
|
|
23
|
+
Requires-Dist: openai>=1.50; extra == 'groq'
|
|
24
|
+
Provides-Extra: openai
|
|
25
|
+
Requires-Dist: openai>=1.50; extra == 'openai'
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# voxprep
|
|
29
|
+
|
|
30
|
+
Get any audio or video file into an AI model, and get the results back on the original timeline.
|
|
31
|
+
|
|
32
|
+
[中文](README_ZH.md)
|
|
33
|
+
|
|
34
|
+
```console
|
|
35
|
+
$ voxprep subtitle meeting.mp4 --via groq
|
|
36
|
+
voxprep: transcribing meeting.mp4 via groq …
|
|
37
|
+
✓ chunk 1/2 (0–1204 s)
|
|
38
|
+
✓ chunk 2/2 (1204–1458 s)
|
|
39
|
+
→ meeting.srt (200 segments, ~2893 LLM tokens)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
A 24-minute video is too big for Groq's 25 MB limit. voxprep decoded it, split it at a pause,
|
|
43
|
+
sent both halves, and shifted the second half's timestamps by 1204 s so the subtitles line up
|
|
44
|
+
with the video.
|
|
45
|
+
|
|
46
|
+
voxprep doesn't do speech recognition itself. It handles the work around the model:
|
|
47
|
+
|
|
48
|
+
- **Before**: decode anything FFmpeg can read, re-encode to what the model wants, split at
|
|
49
|
+
pauses only when the file is over the model's size or length limit.
|
|
50
|
+
- **After**: put each chunk's timestamps back on the source timeline, merge fragments into
|
|
51
|
+
readable cues, and export SRT, VTT, Markdown, JSON, or a Claude document block.
|
|
52
|
+
|
|
53
|
+
It needs only numpy, PyAV (which bundles FFmpeg) and onnxruntime. No PyTorch, no system FFmpeg.
|
|
54
|
+
|
|
55
|
+
## Install
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
pip install --pre voxprep # early alpha; drop --pre once 0.1.0 is out
|
|
59
|
+
pip install --pre "voxprep[openai]" # for the OpenAI and Groq backends
|
|
60
|
+
pip install --pre "voxprep[funasr]" # for local SenseVoice (this one pulls in PyTorch)
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Python 3.12+ on Windows, macOS or Linux.
|
|
64
|
+
|
|
65
|
+
## Usage
|
|
66
|
+
|
|
67
|
+
Built-in backends do everything in one call:
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
voxprep subtitle talk.mp4 --via openai # writes talk.srt (needs OPENAI_API_KEY)
|
|
71
|
+
voxprep transcribe talk.mp4 --via groq -f md # GROQ_API_KEY; formats: srt vtt md txt json claude
|
|
72
|
+
voxprep transcribe talk.mp4 --via funasr # local, no key
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
For any other model, let voxprep prepare the audio and call the model yourself:
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
import voxprep as vp
|
|
79
|
+
|
|
80
|
+
result = vp.prepare("call.m4a", target="openai") # or max_mb=..., max_seconds=..., fmt=...
|
|
81
|
+
texts = [my_model(chunk.to_bytes()) for chunk in result.chunks]
|
|
82
|
+
vp.stitch(result, texts).refine().to_srt("call.srt")
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`stitch` takes whatever your model returns: OpenAI-style JSON with segments, SRT or VTT,
|
|
86
|
+
or plain text. Plain text without timestamps gets spread over the detected speech in that chunk.
|
|
87
|
+
|
|
88
|
+
The same works from the command line:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
voxprep prepare talk.mp4 --for custom --max-mb 10 --max-sec 300 --format wav -o chunks
|
|
92
|
+
# ...send chunks/chunk_000.wav etc. to your model, save answers as chunks/chunk_000.txt...
|
|
93
|
+
voxprep stitch chunks -o talk.srt
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Other commands:
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
voxprep inspect talk.mp4 # duration, format, silence, which models take it as is
|
|
100
|
+
voxprep presets # every preset and its limits
|
|
101
|
+
voxprep ref-clip podcast.mp4 --for f5 # cleanest 3-12 s clip for voice cloning, as ref.wav
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Every command takes `--json`.
|
|
105
|
+
|
|
106
|
+
## Supported models
|
|
107
|
+
|
|
108
|
+
| Preset | Model | Limit voxprep keeps to |
|
|
109
|
+
| --- | --- | --- |
|
|
110
|
+
| `openai` | OpenAI transcription (gpt-transcribe, whisper-1, gpt-4o-*-transcribe) | 24 MB |
|
|
111
|
+
| `groq` | Groq Whisper | 24 MB; avoids chunks under 10 s (billed as 10 s) |
|
|
112
|
+
| `gemini` | Gemini audio, inline | 14 MB, 9.5 h |
|
|
113
|
+
| `sensevoice` | SenseVoice / FunASR | 28 s |
|
|
114
|
+
| `qwen3-asr-flash` | Qwen3-ASR-Flash | 9.5 MB, 290 s (not verified yet) |
|
|
115
|
+
| `f5`, `cosyvoice`, `qwen3-tts`, `generic` | Voice-clone reference clips | 3-30 s depending on model |
|
|
116
|
+
|
|
117
|
+
Anything else: `--for custom` with your own `--max-mb`, `--max-sec`, `--rate` and `--format`.
|
|
118
|
+
|
|
119
|
+
## Claude, ChatGPT, DeepSeek and other text models
|
|
120
|
+
|
|
121
|
+
Most chat models can't take audio. Transcribe first, then hand them the text:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
t = vp.transcribe("meeting.mp4", via="groq")
|
|
125
|
+
t.to_markdown() # "[00:12:41] text" lines, for any model
|
|
126
|
+
t.estimate_tokens() # will it fit in the context window?
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
With Claude you can also get citations back to the exact moment in the recording:
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
import anthropic
|
|
133
|
+
|
|
134
|
+
msg = anthropic.Anthropic().messages.create(
|
|
135
|
+
model="claude-opus-5-5",
|
|
136
|
+
max_tokens=2000,
|
|
137
|
+
messages=[{"role": "user", "content": [
|
|
138
|
+
t.to_claude(title="Weekly meeting"), # document block with citations on
|
|
139
|
+
{"type": "text", "text": "What did we decide about the launch date?"},
|
|
140
|
+
]}],
|
|
141
|
+
)
|
|
142
|
+
for block in msg.content:
|
|
143
|
+
if block.type == "text":
|
|
144
|
+
print(block.text)
|
|
145
|
+
for c in block.citations or []:
|
|
146
|
+
start, end = t.locate(c) # seconds in the recording
|
|
147
|
+
print(f" at {start:.0f}s")
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Coding agents
|
|
151
|
+
|
|
152
|
+
Claude Code, Cursor and the like can't listen to a file, but they can run voxprep.
|
|
153
|
+
|
|
154
|
+
- Claude Code: copy [`skills/voxprep/`](skills/voxprep/SKILL.md) into `~/.claude/skills/`.
|
|
155
|
+
- Others: paste the snippet from [docs/agents.md](docs/agents.md) into your `AGENTS.md` or rules file.
|
|
156
|
+
|
|
157
|
+
## Compared with
|
|
158
|
+
|
|
159
|
+
- **pydub + a loop**: needs system FFmpeg, and you still have to work out each API's limits and
|
|
160
|
+
fix the timestamps yourself.
|
|
161
|
+
- **silero-vad**: great VAD, but pulls in PyTorch. voxprep runs the same model through onnxruntime.
|
|
162
|
+
- **faster-whisper / WhisperX**: the right choice for running Whisper locally. They chunk
|
|
163
|
+
internally, so voxprep isn't needed there.
|
|
164
|
+
|
|
165
|
+
## Testing
|
|
166
|
+
|
|
167
|
+
```bash
|
|
168
|
+
uv run pytest
|
|
169
|
+
uv run python benchmarks/bench_correctness.py
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
The benchmark checks that every chunk stays under its preset's limits, that every cut falls
|
|
173
|
+
in a pause, and that stitched timestamps match the source (within 1 ms).
|
|
174
|
+
|
|
175
|
+
## Notes
|
|
176
|
+
|
|
177
|
+
- Silero VAD v6 (MIT) ships inside the package. Where onnxruntime isn't available, voxprep
|
|
178
|
+
falls back to a simple energy-based VAD.
|
|
179
|
+
- PyAV wheels include FFmpeg libraries (LGPL). Worth checking if you redistribute voxprep in
|
|
180
|
+
another product.
|
|
181
|
+
- Provider limits change. Each preset records its source and when it was checked.
|
|
182
|
+
|
|
183
|
+
MIT license.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
voxprep/__init__.py,sha256=Fxe9HjH_MHDRojr8OH-jp3CCO6E3YFDIwlVolEC8U3c,1163
|
|
2
|
+
voxprep/chunker.py,sha256=z6o1_F2G4yovtlMtP5KljwDh02zcus_iObNHQf-HSAU,14507
|
|
3
|
+
voxprep/cli.py,sha256=CM78WO4D2fdz646aiA3R8tuK6uvW7hJFtJkzUO2GJZw,11712
|
|
4
|
+
voxprep/diagnose.py,sha256=EQ4ZsFK6AdS8ei5JRCV8YVihQO4l5fXUHr_4-CXe-eI,4518
|
|
5
|
+
voxprep/io.py,sha256=Z0T58z5X55lU24n6mRAOn8syp8f6axj_u0R1UfsKeIE,8548
|
|
6
|
+
voxprep/presets.py,sha256=LopevzhBqnzWNVCPlzN68cH9RRxQQMncIF4gNyKdEGQ,7007
|
|
7
|
+
voxprep/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
voxprep/reference.py,sha256=OlruFCUPRvtba02YxtVr5ApBMTRSD1WA323zIEDYJRw,7930
|
|
9
|
+
voxprep/stitch.py,sha256=UHEcFJiiW38RjyoRDo2XB-uFPPQjb7X1wi7l52ogwto,7803
|
|
10
|
+
voxprep/transcript.py,sha256=VWlBD6mASb1XsX3aTWc9YcLBsfN5je4LeEU6WAQ51K4,10388
|
|
11
|
+
voxprep/vad.py,sha256=A-Q-dtyH3IVejni6anm1wtUxkUruFPLUr7Si4A7V-uA,6808
|
|
12
|
+
voxprep/backends/__init__.py,sha256=PSaKpXivQj36Q9lu1M1C2CDux7QYrOaY5ZidOayLP_0,1150
|
|
13
|
+
voxprep/backends/funasr.py,sha256=hIthHsX8FzzXsdyOVCxkpj2Gyr6yalSTz95bAGAq-lk,1815
|
|
14
|
+
voxprep/backends/openai.py,sha256=PzanjohyP9vy7Id4ZN-4XeYQUozdKcjn1FTa1X6AeCo,2776
|
|
15
|
+
voxprep/models/SILERO_VAD_LICENSE,sha256=LmPpo4tuj8DHvDfOF0ysoYYocIVsba9Wl8-3heklUgs,1075
|
|
16
|
+
voxprep/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
17
|
+
voxprep/models/silero_vad_16k_op15.onnx,sha256=WYkjAaSONzEh_ynvUSWYtOX_fruhpGHgXUkPs8IbNUs,1250932
|
|
18
|
+
voxprep-0.1.0.dev0.dist-info/METADATA,sha256=v82YGgIzmtzZmuHLejNv6i8KjvjJu1jzcCg4_eUwDY8,6715
|
|
19
|
+
voxprep-0.1.0.dev0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
20
|
+
voxprep-0.1.0.dev0.dist-info/entry_points.txt,sha256=vdAiX0ByzfyHo3O0mKXac0FlOcBCsKjsHjThbobKTBI,45
|
|
21
|
+
voxprep-0.1.0.dev0.dist-info/licenses/LICENSE,sha256=6rtQZceJ2cv-syHV--NHZRJoq0KPYmv4Q5SoiKUQCR4,1065
|
|
22
|
+
voxprep-0.1.0.dev0.dist-info/RECORD,,
|