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/presets.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Input specs of AI models: how big, how long, what format.
|
|
2
|
+
|
|
3
|
+
Every preset records where its numbers come from and when they were last checked.
|
|
4
|
+
Numbers marked ``verified=None`` come from search snippets and must be re-checked
|
|
5
|
+
against the vendor page before release.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass, field, replace
|
|
11
|
+
|
|
12
|
+
MB = 1_000_000
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class TranscribePreset:
|
|
17
|
+
"""Spec for a speech-to-text or audio-understanding model."""
|
|
18
|
+
|
|
19
|
+
name: str
|
|
20
|
+
description: str
|
|
21
|
+
sample_rate: int = 16000
|
|
22
|
+
fmt: str = "opus" # wav / flac / mp3 / opus
|
|
23
|
+
bitrate: int | None = None # for mp3 / opus
|
|
24
|
+
max_bytes: int | None = None # per request, already including our safety margin
|
|
25
|
+
max_seconds: float | None = None # per request
|
|
26
|
+
min_billed_seconds: float | None = None # requests shorter than this are billed as this
|
|
27
|
+
notes: str = ""
|
|
28
|
+
source: str = ""
|
|
29
|
+
verified: str | None = None # ISO date the numbers were checked against `source`
|
|
30
|
+
kind: str = field(default="transcribe", init=False)
|
|
31
|
+
|
|
32
|
+
def with_limits(self, **changes) -> TranscribePreset:
|
|
33
|
+
return replace(self, **{k: v for k, v in changes.items() if v is not None})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class ClonePreset:
|
|
38
|
+
"""Spec for the reference clip of a voice-cloning TTS model."""
|
|
39
|
+
|
|
40
|
+
name: str
|
|
41
|
+
description: str
|
|
42
|
+
sample_rate: int | None = None # None keeps the source rate
|
|
43
|
+
min_seconds: float = 5.0
|
|
44
|
+
max_seconds: float = 15.0
|
|
45
|
+
ideal_seconds: tuple[float, float] = (6.0, 10.0)
|
|
46
|
+
trailing_silence: float = 0.0 # seconds of silence to append after the clip
|
|
47
|
+
wants_ref_text: bool = True
|
|
48
|
+
notes: str = ""
|
|
49
|
+
source: str = ""
|
|
50
|
+
verified: str | None = None
|
|
51
|
+
kind: str = field(default="clone", init=False)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
TRANSCRIBE: dict[str, TranscribePreset] = {
|
|
55
|
+
p.name: p
|
|
56
|
+
for p in [
|
|
57
|
+
TranscribePreset(
|
|
58
|
+
name="openai",
|
|
59
|
+
description="OpenAI transcription API (gpt-transcribe, whisper-1, gpt-4o-*-transcribe)",
|
|
60
|
+
fmt="opus",
|
|
61
|
+
bitrate=24_000, # 16 kHz speech; ~2 h fits in 24 MB
|
|
62
|
+
max_bytes=24 * MB, # official limit 25 MB per file
|
|
63
|
+
notes="No official duration cap. whisper-1 and gpt-4o-*-transcribe shut down "
|
|
64
|
+
"2027-02-26; gpt-transcribe is the recommended model.",
|
|
65
|
+
source="https://developers.openai.com/api/docs/guides/speech-to-text",
|
|
66
|
+
verified="2026-12-04",
|
|
67
|
+
),
|
|
68
|
+
TranscribePreset(
|
|
69
|
+
name="groq",
|
|
70
|
+
description="Groq Whisper API (free tier; dev tier allows 100 MB via URL)",
|
|
71
|
+
fmt="flac",
|
|
72
|
+
max_bytes=24 * MB, # free tier 25 MB
|
|
73
|
+
min_billed_seconds=10.0,
|
|
74
|
+
notes="Server downsamples to 16 kHz mono. Requests under 10 s are billed as 10 s, "
|
|
75
|
+
"so chunks are kept at 10 s or longer.",
|
|
76
|
+
source="https://console.groq.com/docs/speech-to-text",
|
|
77
|
+
verified="2026-12-04",
|
|
78
|
+
),
|
|
79
|
+
TranscribePreset(
|
|
80
|
+
name="gemini",
|
|
81
|
+
description="Gemini audio understanding, inline request",
|
|
82
|
+
fmt="opus",
|
|
83
|
+
bitrate=24_000,
|
|
84
|
+
max_bytes=14 * MB, # 20 MB inline request limit, minus base64 overhead
|
|
85
|
+
max_seconds=9.5 * 3600,
|
|
86
|
+
notes="Billed at 32 tokens per second of audio. Larger files should use the "
|
|
87
|
+
"Files API, which needs no splitting.",
|
|
88
|
+
source="https://ai.google.dev/gemini-api/docs/audio",
|
|
89
|
+
verified="2026-12-04",
|
|
90
|
+
),
|
|
91
|
+
TranscribePreset(
|
|
92
|
+
name="sensevoice",
|
|
93
|
+
description="SenseVoice / FunASR encoder called directly (no built-in VAD)",
|
|
94
|
+
fmt="wav",
|
|
95
|
+
max_seconds=28.0, # the model is trained on <=30 s inputs
|
|
96
|
+
notes="FunASR AutoModel with vad_model='fsmn-vad' handles long audio itself; "
|
|
97
|
+
"use this preset when calling the model without it.",
|
|
98
|
+
source="https://github.com/FunAudioLLM/SenseVoice",
|
|
99
|
+
verified="2026-12-04",
|
|
100
|
+
),
|
|
101
|
+
TranscribePreset(
|
|
102
|
+
name="qwen3-asr-flash",
|
|
103
|
+
description="Alibaba Qwen3-ASR-Flash (DashScope short-audio endpoint)",
|
|
104
|
+
fmt="mp3",
|
|
105
|
+
bitrate=48_000,
|
|
106
|
+
max_bytes=int(9.5 * MB), # 10 MB
|
|
107
|
+
max_seconds=290.0, # 5 min
|
|
108
|
+
source="https://www.alibabacloud.com/help/model-studio/qwen-speech-recognition",
|
|
109
|
+
verified=None,
|
|
110
|
+
),
|
|
111
|
+
]
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
CLONE: dict[str, ClonePreset] = {
|
|
115
|
+
p.name: p
|
|
116
|
+
for p in [
|
|
117
|
+
ClonePreset(
|
|
118
|
+
name="f5",
|
|
119
|
+
description="F5-TTS",
|
|
120
|
+
sample_rate=24000,
|
|
121
|
+
min_seconds=3.0,
|
|
122
|
+
max_seconds=12.0,
|
|
123
|
+
ideal_seconds=(6.0, 10.0),
|
|
124
|
+
trailing_silence=1.0,
|
|
125
|
+
wants_ref_text=True,
|
|
126
|
+
notes="Clips over ~12 s are truncated. Reference text is optional (auto-transcribed).",
|
|
127
|
+
source="https://github.com/SWivid/F5-TTS/tree/main/src/f5_tts/infer",
|
|
128
|
+
verified="2026-12-04",
|
|
129
|
+
),
|
|
130
|
+
ClonePreset(
|
|
131
|
+
name="cosyvoice",
|
|
132
|
+
description="CosyVoice 2 / 3",
|
|
133
|
+
sample_rate=16000,
|
|
134
|
+
min_seconds=3.0,
|
|
135
|
+
max_seconds=30.0,
|
|
136
|
+
ideal_seconds=(5.0, 10.0),
|
|
137
|
+
wants_ref_text=True,
|
|
138
|
+
source="https://github.com/FunAudioLLM/CosyVoice",
|
|
139
|
+
verified="2026-12-04",
|
|
140
|
+
),
|
|
141
|
+
ClonePreset(
|
|
142
|
+
name="qwen3-tts",
|
|
143
|
+
description="Qwen3-TTS voice clone",
|
|
144
|
+
sample_rate=24000,
|
|
145
|
+
min_seconds=3.0,
|
|
146
|
+
max_seconds=15.0,
|
|
147
|
+
ideal_seconds=(5.0, 10.0),
|
|
148
|
+
wants_ref_text=True,
|
|
149
|
+
notes="Standard mode needs ref_text; x_vector_only_mode works without it "
|
|
150
|
+
"at lower quality.",
|
|
151
|
+
source="https://github.com/QwenLM/Qwen3-TTS",
|
|
152
|
+
verified="2026-12-04",
|
|
153
|
+
),
|
|
154
|
+
ClonePreset(
|
|
155
|
+
name="generic",
|
|
156
|
+
description="Any voice-cloning model",
|
|
157
|
+
sample_rate=None,
|
|
158
|
+
min_seconds=5.0,
|
|
159
|
+
max_seconds=15.0,
|
|
160
|
+
ideal_seconds=(6.0, 10.0),
|
|
161
|
+
),
|
|
162
|
+
]
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def get(name: str) -> TranscribePreset | ClonePreset:
|
|
167
|
+
if name in TRANSCRIBE:
|
|
168
|
+
return TRANSCRIBE[name]
|
|
169
|
+
if name in CLONE:
|
|
170
|
+
return CLONE[name]
|
|
171
|
+
raise KeyError(f"unknown preset {name!r}; available: {', '.join(names())}")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def names() -> list[str]:
|
|
175
|
+
return [*TRANSCRIBE, *CLONE]
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def custom(
|
|
179
|
+
max_mb: float | None = None,
|
|
180
|
+
max_seconds: float | None = None,
|
|
181
|
+
sample_rate: int = 16000,
|
|
182
|
+
fmt: str = "opus",
|
|
183
|
+
bitrate: int | None = None,
|
|
184
|
+
min_billed_seconds: float | None = None,
|
|
185
|
+
) -> TranscribePreset:
|
|
186
|
+
"""A preset for any model, built from its limits."""
|
|
187
|
+
return TranscribePreset(
|
|
188
|
+
name="custom",
|
|
189
|
+
description="User-defined limits",
|
|
190
|
+
sample_rate=sample_rate,
|
|
191
|
+
fmt=fmt,
|
|
192
|
+
bitrate=bitrate,
|
|
193
|
+
max_bytes=int(max_mb * MB) if max_mb else None,
|
|
194
|
+
max_seconds=max_seconds,
|
|
195
|
+
min_billed_seconds=min_billed_seconds,
|
|
196
|
+
)
|
voxprep/py.typed
ADDED
|
File without changes
|
voxprep/reference.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
"""Pick the cleanest stretch of continuous speech as a voice-cloning reference clip.
|
|
2
|
+
|
|
3
|
+
Candidates are runs of speech without long pauses that fit the target model's length.
|
|
4
|
+
Each is scored on signal-to-noise against the recording's own noise floor, how much of
|
|
5
|
+
it is speech, VAD confidence, loudness steadiness, level, length fit, and clipping.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import asdict, dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from . import io, presets, vad
|
|
16
|
+
from .io import Audio
|
|
17
|
+
from .vad import Span
|
|
18
|
+
|
|
19
|
+
MAX_INNER_GAP = 0.5 # seconds of pause allowed inside a reference clip
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Candidate:
|
|
24
|
+
start: float
|
|
25
|
+
end: float
|
|
26
|
+
score: float
|
|
27
|
+
snr_db: float
|
|
28
|
+
speech_ratio: float
|
|
29
|
+
confidence: float
|
|
30
|
+
stability_db: float
|
|
31
|
+
level_dbfs: float
|
|
32
|
+
clipping: float
|
|
33
|
+
text: str | None = None
|
|
34
|
+
audio: Audio | None = field(default=None, repr=False)
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def duration(self) -> float:
|
|
38
|
+
return self.end - self.start
|
|
39
|
+
|
|
40
|
+
def save(self, path: str | Path, text_path: str | Path | None = None) -> Path:
|
|
41
|
+
"""Write the clip as WAV; write ``text`` next to it (``.txt``) when known."""
|
|
42
|
+
path = Path(path)
|
|
43
|
+
if self.audio is None:
|
|
44
|
+
raise ValueError("candidate has no audio")
|
|
45
|
+
self.audio.save(path, "wav")
|
|
46
|
+
if self.text:
|
|
47
|
+
Path(text_path or path.with_suffix(".txt")).write_text(self.text + "\n", "utf-8")
|
|
48
|
+
return path
|
|
49
|
+
|
|
50
|
+
def to_dict(self) -> dict:
|
|
51
|
+
d = asdict(self)
|
|
52
|
+
d.pop("audio")
|
|
53
|
+
d["duration"] = round(self.duration, 3)
|
|
54
|
+
return {k: (round(v, 4) if isinstance(v, float) else v) for k, v in d.items()}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def extract_reference(
|
|
58
|
+
source: io.Source | Audio,
|
|
59
|
+
target: str | presets.ClonePreset = "generic",
|
|
60
|
+
*,
|
|
61
|
+
top: int = 3,
|
|
62
|
+
min_seconds: float | None = None,
|
|
63
|
+
max_seconds: float | None = None,
|
|
64
|
+
vad_backend: str = "auto",
|
|
65
|
+
transcribe_with=None,
|
|
66
|
+
) -> list[Candidate]:
|
|
67
|
+
"""Best reference clips for voice cloning, best first.
|
|
68
|
+
|
|
69
|
+
``target`` is a clone preset (``f5``, ``cosyvoice``, ``qwen3-tts``, ``generic``).
|
|
70
|
+
``transcribe_with`` (a backend name or object) fills in each clip's ``text``, which
|
|
71
|
+
most cloning models want as the reference transcript.
|
|
72
|
+
"""
|
|
73
|
+
preset = presets.get(target) if isinstance(target, str) else target
|
|
74
|
+
if not isinstance(preset, presets.ClonePreset):
|
|
75
|
+
raise ValueError(f"{preset.name!r} is not a voice-clone preset")
|
|
76
|
+
lo = min_seconds or preset.min_seconds
|
|
77
|
+
hi = max_seconds or preset.max_seconds
|
|
78
|
+
|
|
79
|
+
if isinstance(source, Audio):
|
|
80
|
+
a16 = source.resample(vad.SAMPLE_RATE)
|
|
81
|
+
out_audio = source.resample(preset.sample_rate) if preset.sample_rate else source
|
|
82
|
+
else:
|
|
83
|
+
a16 = io.load(source, vad.SAMPLE_RATE)
|
|
84
|
+
rate = preset.sample_rate or (a16.source.sample_rate if a16.source else vad.SAMPLE_RATE)
|
|
85
|
+
out_audio = a16 if rate == vad.SAMPLE_RATE else io.load(source, rate)
|
|
86
|
+
|
|
87
|
+
probs = vad.probabilities(a16, vad_backend)
|
|
88
|
+
spans = vad.speech_spans(probs, a16.duration, min_silence=0.15, min_speech=0.2, pad=0.05)
|
|
89
|
+
windows = _windows(spans, lo, hi, MAX_INNER_GAP) or _windows(spans, lo, hi, 1.5)
|
|
90
|
+
|
|
91
|
+
rms_db = _frame_db(a16.samples)
|
|
92
|
+
n = min(len(rms_db), len(probs))
|
|
93
|
+
rms_db, probs = rms_db[:n], probs[:n]
|
|
94
|
+
quiet = rms_db[probs < 0.2]
|
|
95
|
+
floor = float(np.median(quiet)) if len(quiet) >= 10 else float(np.percentile(rms_db, 10))
|
|
96
|
+
|
|
97
|
+
scored = [_score(w, a16, rms_db, probs, floor, preset, lo, hi) for w in windows]
|
|
98
|
+
scored.sort(key=lambda c: c.score, reverse=True)
|
|
99
|
+
|
|
100
|
+
picked: list[Candidate] = []
|
|
101
|
+
for c in scored:
|
|
102
|
+
if all(c.end <= p.start or c.start >= p.end for p in picked):
|
|
103
|
+
picked.append(c)
|
|
104
|
+
if len(picked) == top:
|
|
105
|
+
break
|
|
106
|
+
|
|
107
|
+
backend = None
|
|
108
|
+
if transcribe_with is not None:
|
|
109
|
+
from .backends import get_backend
|
|
110
|
+
|
|
111
|
+
backend = (
|
|
112
|
+
get_backend(transcribe_with) if isinstance(transcribe_with, str) else transcribe_with
|
|
113
|
+
)
|
|
114
|
+
for c in picked:
|
|
115
|
+
c.audio = _finish(out_audio.slice(c.start, c.end), preset.trailing_silence)
|
|
116
|
+
if backend is not None:
|
|
117
|
+
c.text = _transcribe_clip(backend, a16.slice(c.start, c.end), c.start)
|
|
118
|
+
return picked
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _windows(spans: list[Span], lo: float, hi: float, max_gap: float) -> list[Span]:
|
|
122
|
+
"""Stretches of consecutive speech spans, pauses <= ``max_gap``, length in [lo, hi]."""
|
|
123
|
+
out = []
|
|
124
|
+
for i, first in enumerate(spans):
|
|
125
|
+
for j in range(i, len(spans)):
|
|
126
|
+
if j > i and spans[j].start - spans[j - 1].end > max_gap:
|
|
127
|
+
break
|
|
128
|
+
length = spans[j].end - first.start
|
|
129
|
+
if length > hi:
|
|
130
|
+
break
|
|
131
|
+
if length >= lo:
|
|
132
|
+
out.append(Span(first.start, spans[j].end))
|
|
133
|
+
return out
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _frame_db(x: np.ndarray) -> np.ndarray:
|
|
137
|
+
n = len(x) // vad.WINDOW
|
|
138
|
+
frames = x[: n * vad.WINDOW].reshape(n, vad.WINDOW)
|
|
139
|
+
return 10 * np.log10(np.mean(frames**2, axis=1) + 1e-10)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _score(w, a16, rms_db, probs, floor, preset, lo, hi) -> Candidate:
|
|
143
|
+
i, j = (
|
|
144
|
+
int(w.start / vad.FRAME_SEC),
|
|
145
|
+
max(int(w.start / vad.FRAME_SEC) + 1, int(w.end / vad.FRAME_SEC)),
|
|
146
|
+
)
|
|
147
|
+
db, p = rms_db[i:j], probs[i:j]
|
|
148
|
+
speech = p >= 0.5
|
|
149
|
+
sp_db = db[speech] if speech.any() else db
|
|
150
|
+
level = float(10 * np.log10(np.mean(10 ** (sp_db / 10))))
|
|
151
|
+
local_quiet = db[p < 0.2]
|
|
152
|
+
noise = max(floor, float(np.median(local_quiet))) if len(local_quiet) >= 3 else floor
|
|
153
|
+
snr = level - noise
|
|
154
|
+
ratio = float(speech.mean()) if len(p) else 0.0
|
|
155
|
+
conf = float(p[speech].mean()) if speech.any() else 0.0
|
|
156
|
+
stability = float(np.std(sp_db))
|
|
157
|
+
x = a16.slice(w.start, w.end).samples
|
|
158
|
+
clipping = float(np.mean(np.abs(x) >= 0.99)) if len(x) else 0.0
|
|
159
|
+
|
|
160
|
+
ideal_lo, ideal_hi = preset.ideal_seconds
|
|
161
|
+
d = w.duration
|
|
162
|
+
off = max(ideal_lo - d, d - ideal_hi, 0.0)
|
|
163
|
+
parts = {
|
|
164
|
+
"snr": _clip((snr - 10) / 30),
|
|
165
|
+
"ratio": _clip((ratio - 0.6) / 0.35),
|
|
166
|
+
"conf": _clip((conf - 0.6) / 0.35),
|
|
167
|
+
"stability": _clip(1 - (stability - 6) / 12),
|
|
168
|
+
"level": _clip(1 - max(-35 - level, level + 10, 0) / 15),
|
|
169
|
+
"length": _clip(1 - off / 5),
|
|
170
|
+
}
|
|
171
|
+
weights = {
|
|
172
|
+
"snr": 0.35,
|
|
173
|
+
"ratio": 0.15,
|
|
174
|
+
"conf": 0.15,
|
|
175
|
+
"stability": 0.1,
|
|
176
|
+
"level": 0.1,
|
|
177
|
+
"length": 0.15,
|
|
178
|
+
}
|
|
179
|
+
score = sum(parts[k] * weights[k] for k in parts) * (1 - min(1.0, clipping * 500))
|
|
180
|
+
return Candidate(
|
|
181
|
+
start=round(w.start, 3),
|
|
182
|
+
end=round(w.end, 3),
|
|
183
|
+
score=round(score, 4),
|
|
184
|
+
snr_db=round(snr, 2),
|
|
185
|
+
speech_ratio=round(ratio, 3),
|
|
186
|
+
confidence=round(conf, 3),
|
|
187
|
+
stability_db=round(stability, 2),
|
|
188
|
+
level_dbfs=round(level, 2),
|
|
189
|
+
clipping=round(clipping, 6),
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _finish(audio: Audio, trailing_silence: float) -> Audio:
|
|
194
|
+
"""Short fades, peak-normalise to -1 dBFS, and append the silence some models want."""
|
|
195
|
+
x = audio.samples.astype(np.float32).copy()
|
|
196
|
+
fade = min(len(x) // 4, int(0.01 * audio.sample_rate))
|
|
197
|
+
if fade > 0:
|
|
198
|
+
ramp = np.linspace(0, 1, fade, dtype=np.float32)
|
|
199
|
+
x[:fade] *= ramp
|
|
200
|
+
x[-fade:] *= ramp[::-1]
|
|
201
|
+
peak = float(np.max(np.abs(x))) if len(x) else 0.0
|
|
202
|
+
if peak > 0:
|
|
203
|
+
x *= 0.891 / peak
|
|
204
|
+
if trailing_silence > 0:
|
|
205
|
+
x = np.concatenate([x, np.zeros(int(trailing_silence * audio.sample_rate), np.float32)])
|
|
206
|
+
return Audio(x, audio.sample_rate, audio.source)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _transcribe_clip(backend, clip16: Audio, start: float) -> str | None:
|
|
210
|
+
from .chunker import Chunk, Piece
|
|
211
|
+
from .stitch import _plain_text
|
|
212
|
+
|
|
213
|
+
fmt = presets.TRANSCRIBE[backend.preset].fmt if backend.preset in presets.TRANSCRIBE else "wav"
|
|
214
|
+
chunk = Chunk(0, [Piece(0.0, start, clip16.duration)], [], fmt, audio=clip16)
|
|
215
|
+
text = _plain_text(backend.transcribe(chunk))
|
|
216
|
+
return text.strip() if text else None
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _clip(v: float) -> float:
|
|
220
|
+
return float(min(1.0, max(0.0, v)))
|
voxprep/stitch.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Put per-chunk model results back on the original file's timeline."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import zlib
|
|
8
|
+
from collections.abc import Callable, Sequence
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .chunker import Chunk, PreparedResult, prepare
|
|
12
|
+
from .transcript import Segment, Transcript, share_time, split_sentences
|
|
13
|
+
from .vad import Span
|
|
14
|
+
|
|
15
|
+
_CUE_TIME = re.compile(
|
|
16
|
+
r"(?:(\d+):)?(\d{1,2}):(\d{2})[,.](\d{1,3})\s*-->\s*(?:(\d+):)?(\d{1,2}):(\d{2})[,.](\d{1,3})"
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def stitch(result: PreparedResult | str | Path, transcripts: Sequence) -> Transcript:
|
|
21
|
+
"""Merge one result per chunk into a single :class:`Transcript` on the source timeline.
|
|
22
|
+
|
|
23
|
+
Each item may be: a :class:`Transcript`; an API response (OpenAI / Groq
|
|
24
|
+
``verbose_json`` or ``json``, as a dict or SDK object); SRT / VTT text; plain text; or
|
|
25
|
+
a path to a ``.json`` / ``.srt`` / ``.vtt`` / ``.txt`` file. Plain text without times
|
|
26
|
+
is spread over the chunk's detected speech, sentence by sentence.
|
|
27
|
+
"""
|
|
28
|
+
if not isinstance(result, PreparedResult):
|
|
29
|
+
result = PreparedResult.load(result)
|
|
30
|
+
if len(transcripts) != len(result.chunks):
|
|
31
|
+
raise ValueError(f"got {len(transcripts)} results for {len(result.chunks)} chunks")
|
|
32
|
+
|
|
33
|
+
segments: list[Segment] = []
|
|
34
|
+
language = None
|
|
35
|
+
for chunk, item in zip(result.chunks, transcripts, strict=True):
|
|
36
|
+
local, lang = to_local_segments(item, chunk)
|
|
37
|
+
language = language or lang
|
|
38
|
+
for s in local:
|
|
39
|
+
a = chunk.to_source_time(min(s.start, chunk.duration))
|
|
40
|
+
b = chunk.to_source_time(min(s.end, chunk.duration))
|
|
41
|
+
if segments and a < segments[-1].end: # keep the timeline monotonic
|
|
42
|
+
a = segments[-1].end
|
|
43
|
+
if b <= a:
|
|
44
|
+
b = a + 0.01
|
|
45
|
+
if s.text.strip():
|
|
46
|
+
segments.append(Segment(round(a, 3), round(b, 3), s.text.strip(), s.speaker))
|
|
47
|
+
return Transcript(segments, language, result.duration)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def transcribe(
|
|
51
|
+
source,
|
|
52
|
+
via="openai",
|
|
53
|
+
*,
|
|
54
|
+
strip_silence: bool = False,
|
|
55
|
+
on_chunk: Callable[[Chunk, int], None] | None = None,
|
|
56
|
+
**backend_options,
|
|
57
|
+
) -> Transcript:
|
|
58
|
+
"""Prepare ``source`` for backend ``via``, transcribe every chunk, and stitch the results.
|
|
59
|
+
|
|
60
|
+
``via`` is a backend name (``openai``, ``groq``, ``funasr``) or any object with a
|
|
61
|
+
``preset`` attribute and a ``transcribe(chunk, prompt)`` method.
|
|
62
|
+
"""
|
|
63
|
+
from .backends import get_backend
|
|
64
|
+
|
|
65
|
+
backend = get_backend(via, **backend_options) if isinstance(via, str) else via
|
|
66
|
+
result = (
|
|
67
|
+
source
|
|
68
|
+
if isinstance(source, PreparedResult)
|
|
69
|
+
else prepare(source, backend.preset, strip_silence=strip_silence)
|
|
70
|
+
)
|
|
71
|
+
outputs, prompt = [], None
|
|
72
|
+
for chunk in result.chunks:
|
|
73
|
+
out = backend.transcribe(chunk, prompt)
|
|
74
|
+
outputs.append(out)
|
|
75
|
+
# the previous chunk's words give the next one context, unless the model was looping
|
|
76
|
+
prompt = context_prompt(_plain_text(out)) or prompt
|
|
77
|
+
if on_chunk:
|
|
78
|
+
on_chunk(chunk, len(result.chunks))
|
|
79
|
+
return stitch(result, outputs)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def context_prompt(text: str | None, limit: int = 200) -> str | None:
|
|
83
|
+
"""The tail of ``text`` to pass as the next chunk's prompt, or None if it looks repetitive.
|
|
84
|
+
|
|
85
|
+
Prompting with a looping transcript ("thank you. thank you. thank you.") makes Whisper-style
|
|
86
|
+
models loop too, so repetitive text is dropped. Same idea as Whisper's own compression-ratio
|
|
87
|
+
check (> 2.4 means hallucinated repetition).
|
|
88
|
+
"""
|
|
89
|
+
if not text or not text.strip():
|
|
90
|
+
return None
|
|
91
|
+
window = text.strip()[-1000:]
|
|
92
|
+
sentences = [x.strip().lower() for x in split_sentences(window)]
|
|
93
|
+
if len(sentences) >= 4 and len(set(sentences)) / len(sentences) < 0.6:
|
|
94
|
+
return None
|
|
95
|
+
raw = window.encode("utf-8")
|
|
96
|
+
if len(raw) >= 200 and len(raw) / len(zlib.compress(raw)) > 2.4:
|
|
97
|
+
return None
|
|
98
|
+
return window[-limit:]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# ---------- parsing one chunk's result ----------
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def to_local_segments(item, chunk: Chunk) -> tuple[list[Segment], str | None]:
|
|
105
|
+
"""Segments in chunk-local seconds, plus the language if the result reports one."""
|
|
106
|
+
if item is None:
|
|
107
|
+
return [], None
|
|
108
|
+
if isinstance(item, Transcript):
|
|
109
|
+
return list(item.segments), item.language
|
|
110
|
+
if isinstance(item, Path) or (isinstance(item, str) and _looks_like_path(item)):
|
|
111
|
+
return _from_file(Path(item), chunk)
|
|
112
|
+
if hasattr(item, "model_dump"): # OpenAI / Groq SDK objects
|
|
113
|
+
item = item.model_dump()
|
|
114
|
+
elif not isinstance(item, (dict, str)) and hasattr(item, "to_dict"):
|
|
115
|
+
item = item.to_dict()
|
|
116
|
+
if isinstance(item, dict):
|
|
117
|
+
lang = item.get("language")
|
|
118
|
+
segs = item.get("segments") or []
|
|
119
|
+
if segs and all("start" in s and "end" in s for s in segs):
|
|
120
|
+
return [
|
|
121
|
+
Segment(
|
|
122
|
+
float(s["start"]), float(s["end"]), str(s.get("text", "")), s.get("speaker")
|
|
123
|
+
)
|
|
124
|
+
for s in segs
|
|
125
|
+
], lang
|
|
126
|
+
return spread_text(str(item.get("text", "")), chunk), lang
|
|
127
|
+
if isinstance(item, str):
|
|
128
|
+
if "-->" in item:
|
|
129
|
+
return parse_cues(item), None
|
|
130
|
+
return spread_text(item, chunk), None
|
|
131
|
+
raise TypeError(f"don't know how to read a {type(item).__name__} result")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def spread_text(text: str, chunk: Chunk) -> list[Segment]:
|
|
135
|
+
"""Give untimed text times by spreading its sentences over the chunk's speech."""
|
|
136
|
+
sentences = split_sentences(text.strip()) or ([text.strip()] if text.strip() else [])
|
|
137
|
+
if not sentences:
|
|
138
|
+
return []
|
|
139
|
+
spans = chunk.speech or [Span(0.0, chunk.duration)]
|
|
140
|
+
total = sum(s.duration for s in spans)
|
|
141
|
+
ranges = share_time(sentences, 0.0, total)
|
|
142
|
+
return [
|
|
143
|
+
Segment(round(_speech_to_local(a, spans), 3), round(_speech_to_local(b, spans), 3), t)
|
|
144
|
+
for t, (a, b) in zip(sentences, ranges, strict=True)
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _speech_to_local(x: float, spans: list[Span]) -> float:
|
|
149
|
+
"""Map ``x`` seconds of accumulated speech to a chunk-local time."""
|
|
150
|
+
acc = 0.0
|
|
151
|
+
for s in spans:
|
|
152
|
+
if x <= acc + s.duration:
|
|
153
|
+
return s.start + (x - acc)
|
|
154
|
+
acc += s.duration
|
|
155
|
+
return spans[-1].end
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def parse_cues(text: str) -> list[Segment]:
|
|
159
|
+
"""Parse SRT or WebVTT cues."""
|
|
160
|
+
segs = []
|
|
161
|
+
blocks = re.split(r"\n\s*\n", text.replace("\r\n", "\n").strip())
|
|
162
|
+
for block in blocks:
|
|
163
|
+
lines = block.strip().split("\n")
|
|
164
|
+
for i, line in enumerate(lines):
|
|
165
|
+
m = _CUE_TIME.search(line)
|
|
166
|
+
if m:
|
|
167
|
+
g = m.groups()
|
|
168
|
+
start = _secs(g[0], g[1], g[2], g[3])
|
|
169
|
+
end = _secs(g[4], g[5], g[6], g[7])
|
|
170
|
+
body = " ".join(x.strip() for x in lines[i + 1 :] if x.strip())
|
|
171
|
+
body = re.sub(r"<[^>]+>", "", body)
|
|
172
|
+
if body:
|
|
173
|
+
segs.append(Segment(start, end, body))
|
|
174
|
+
break
|
|
175
|
+
return segs
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _secs(h, m, s, ms) -> float:
|
|
179
|
+
return int(h or 0) * 3600 + int(m) * 60 + int(s) + int(ms.ljust(3, "0")) / 1000
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _from_file(path: Path, chunk: Chunk) -> tuple[list[Segment], str | None]:
|
|
183
|
+
text = path.read_text(encoding="utf-8")
|
|
184
|
+
if path.suffix.lower() == ".json":
|
|
185
|
+
return to_local_segments(json.loads(text), chunk)
|
|
186
|
+
if path.suffix.lower() in (".srt", ".vtt"):
|
|
187
|
+
return parse_cues(text), None
|
|
188
|
+
return spread_text(text, chunk), None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _looks_like_path(s: str) -> bool:
|
|
192
|
+
return "\n" not in s and len(s) < 260 and s.lower().endswith((".json", ".srt", ".vtt", ".txt"))
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _plain_text(out) -> str | None:
|
|
196
|
+
if out is None:
|
|
197
|
+
return None
|
|
198
|
+
if isinstance(out, Transcript):
|
|
199
|
+
return out.text
|
|
200
|
+
if hasattr(out, "model_dump"):
|
|
201
|
+
out = out.model_dump()
|
|
202
|
+
if isinstance(out, dict):
|
|
203
|
+
return out.get("text")
|
|
204
|
+
return str(out) if isinstance(out, str) else None
|