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/cli.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"""Command line: ``voxprep <command> [--json]``.
|
|
2
|
+
|
|
3
|
+
Human-readable output by default; ``--json`` prints one JSON object for scripts and agents.
|
|
4
|
+
Progress goes to stderr so stdout stays clean.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
from dataclasses import asdict
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from . import __version__, presets
|
|
17
|
+
from .chunker import MANIFEST, PreparedResult, prepare
|
|
18
|
+
from .diagnose import inspect
|
|
19
|
+
from .reference import extract_reference
|
|
20
|
+
from .stitch import stitch, transcribe
|
|
21
|
+
|
|
22
|
+
OUTPUT_FORMATS = ["srt", "vtt", "md", "txt", "json", "claude"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _print_json(obj) -> None:
|
|
26
|
+
json.dump(obj, sys.stdout, ensure_ascii=False, indent=2)
|
|
27
|
+
sys.stdout.write("\n")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _say(msg: str) -> None:
|
|
31
|
+
print(msg, file=sys.stderr, flush=True)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ---------- inspect / presets ----------
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cmd_inspect(args: argparse.Namespace) -> int:
|
|
38
|
+
report = inspect(args.file, vad_backend=args.vad)
|
|
39
|
+
if args.json:
|
|
40
|
+
_print_json(report.to_dict())
|
|
41
|
+
else:
|
|
42
|
+
print(report.summary())
|
|
43
|
+
return 0
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def cmd_presets(args: argparse.Namespace) -> int:
|
|
47
|
+
if args.json:
|
|
48
|
+
_print_json(
|
|
49
|
+
{
|
|
50
|
+
"transcribe": [asdict(p) for p in presets.TRANSCRIBE.values()],
|
|
51
|
+
"clone": [asdict(p) for p in presets.CLONE.values()],
|
|
52
|
+
}
|
|
53
|
+
)
|
|
54
|
+
return 0
|
|
55
|
+
print("Transcription / understanding (voxprep prepare FILE --for NAME)")
|
|
56
|
+
for p in presets.TRANSCRIBE.values():
|
|
57
|
+
limits = []
|
|
58
|
+
if p.max_bytes:
|
|
59
|
+
limits.append(f"≤{p.max_bytes / 1e6:g} MB")
|
|
60
|
+
if p.max_seconds:
|
|
61
|
+
limits.append(f"≤{p.max_seconds:g} s")
|
|
62
|
+
if p.min_billed_seconds:
|
|
63
|
+
limits.append(f"billed ≥{p.min_billed_seconds:g} s")
|
|
64
|
+
flag = "" if p.verified else " (unverified)"
|
|
65
|
+
spec = f"{p.sample_rate} Hz {p.fmt:5s} {', '.join(limits):28s}"
|
|
66
|
+
print(f" {p.name:16s} {spec} {p.description}{flag}")
|
|
67
|
+
print("\nVoice clone reference (voxprep ref-clip FILE --for NAME)")
|
|
68
|
+
for p in presets.CLONE.values():
|
|
69
|
+
rate = f"{p.sample_rate} Hz" if p.sample_rate else "source rate"
|
|
70
|
+
print(
|
|
71
|
+
f" {p.name:16s} {rate:11s} {p.min_seconds:g}–{p.max_seconds:g} s "
|
|
72
|
+
f"(ideal {p.ideal_seconds[0]:g}–{p.ideal_seconds[1]:g} s) {p.description}"
|
|
73
|
+
)
|
|
74
|
+
print(
|
|
75
|
+
"\nAny other model: voxprep prepare FILE --max-mb N --max-sec N --format wav|flac|mp3|opus"
|
|
76
|
+
)
|
|
77
|
+
return 0
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# ---------- prepare / stitch ----------
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def cmd_prepare(args: argparse.Namespace) -> int:
|
|
84
|
+
result = prepare(
|
|
85
|
+
args.file,
|
|
86
|
+
args.target,
|
|
87
|
+
strip_silence=args.strip_silence,
|
|
88
|
+
vad_backend=args.vad,
|
|
89
|
+
max_mb=args.max_mb,
|
|
90
|
+
max_seconds=args.max_sec,
|
|
91
|
+
sample_rate=args.rate,
|
|
92
|
+
fmt=args.format,
|
|
93
|
+
bitrate=args.bitrate,
|
|
94
|
+
)
|
|
95
|
+
out = Path(args.output or f"{Path(args.file).stem}_{result.preset.name}")
|
|
96
|
+
manifest = result.save(out)
|
|
97
|
+
if args.json:
|
|
98
|
+
_print_json({"manifest": str(manifest), **result.to_dict()})
|
|
99
|
+
else:
|
|
100
|
+
print(result.summary())
|
|
101
|
+
print(f"→ {out}{os.sep} (manifest: {manifest.name})")
|
|
102
|
+
return 0
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def cmd_stitch(args: argparse.Namespace) -> int:
|
|
106
|
+
manifest = Path(args.manifest)
|
|
107
|
+
result = PreparedResult.load(manifest)
|
|
108
|
+
folder = manifest if manifest.is_dir() else manifest.parent
|
|
109
|
+
files = [Path(r) for r in args.results]
|
|
110
|
+
if len(files) == 1 and files[0].is_dir():
|
|
111
|
+
files = _results_in(files[0], len(result.chunks))
|
|
112
|
+
elif not files:
|
|
113
|
+
files = _results_in(folder, len(result.chunks))
|
|
114
|
+
transcript = stitch(result, files)
|
|
115
|
+
if not args.no_refine:
|
|
116
|
+
transcript = transcript.refine()
|
|
117
|
+
return _emit(transcript, args, default_name=None)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _results_in(folder: Path, n: int) -> list[Path]:
|
|
121
|
+
found = []
|
|
122
|
+
for i in range(n):
|
|
123
|
+
for ext in (".json", ".srt", ".vtt", ".txt"):
|
|
124
|
+
p = folder / f"chunk_{i:03d}{ext}"
|
|
125
|
+
if p.exists() and p.name != MANIFEST:
|
|
126
|
+
found.append(p)
|
|
127
|
+
break
|
|
128
|
+
else:
|
|
129
|
+
raise FileNotFoundError(
|
|
130
|
+
f"no result for chunk {i} (expected chunk_{i:03d}.json/.srt/.vtt/.txt)"
|
|
131
|
+
)
|
|
132
|
+
return found
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# ---------- subtitle / transcribe ----------
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def cmd_subtitle(args: argparse.Namespace) -> int:
|
|
139
|
+
options = {k: v for k, v in {"model": args.model, "language": args.language}.items() if v}
|
|
140
|
+
|
|
141
|
+
def progress(chunk, total):
|
|
142
|
+
_say(f" ✓ chunk {chunk.index + 1}/{total} ({chunk.start:.0f}–{chunk.end:.0f} s)")
|
|
143
|
+
|
|
144
|
+
_say(f"voxprep: transcribing {args.file} via {args.via} …")
|
|
145
|
+
transcript = transcribe(
|
|
146
|
+
args.file, via=args.via, strip_silence=args.strip_silence, on_chunk=progress, **options
|
|
147
|
+
)
|
|
148
|
+
if not args.no_refine:
|
|
149
|
+
transcript = transcript.refine()
|
|
150
|
+
return _emit(transcript, args, default_name=Path(args.file).with_suffix(".srt"))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _emit(transcript, args, default_name) -> int:
|
|
154
|
+
out = Path(args.output) if args.output else default_name
|
|
155
|
+
fmt = args.format
|
|
156
|
+
if out is None and not fmt: # stitch without -o: print SRT, or JSON for --json
|
|
157
|
+
if args.json:
|
|
158
|
+
_print_json(transcript.to_dict())
|
|
159
|
+
else:
|
|
160
|
+
sys.stdout.write(transcript.to_srt())
|
|
161
|
+
return 0
|
|
162
|
+
if out is None:
|
|
163
|
+
out = Path(f"transcript.{'claude.json' if fmt == 'claude' else fmt}")
|
|
164
|
+
transcript.save(out, fmt)
|
|
165
|
+
info = {
|
|
166
|
+
"output": str(out),
|
|
167
|
+
"format": fmt or out.suffix.lstrip("."),
|
|
168
|
+
"segments": len(transcript.segments),
|
|
169
|
+
"duration": transcript.duration,
|
|
170
|
+
"language": transcript.language,
|
|
171
|
+
"estimated_llm_tokens": transcript.estimate_tokens(),
|
|
172
|
+
}
|
|
173
|
+
if args.json:
|
|
174
|
+
_print_json(info)
|
|
175
|
+
else:
|
|
176
|
+
print(f"→ {out} ({info['segments']} segments, ~{info['estimated_llm_tokens']} LLM tokens)")
|
|
177
|
+
return 0
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# ---------- ref-clip ----------
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def cmd_ref_clip(args: argparse.Namespace) -> int:
|
|
184
|
+
candidates = extract_reference(
|
|
185
|
+
args.file,
|
|
186
|
+
args.target,
|
|
187
|
+
top=args.top,
|
|
188
|
+
min_seconds=args.min_sec,
|
|
189
|
+
max_seconds=args.max_sec,
|
|
190
|
+
vad_backend=args.vad,
|
|
191
|
+
transcribe_with=args.via,
|
|
192
|
+
)
|
|
193
|
+
if not candidates:
|
|
194
|
+
print("voxprep: no stretch of continuous speech long enough was found", file=sys.stderr)
|
|
195
|
+
return 1
|
|
196
|
+
out = Path(args.output or "ref.wav")
|
|
197
|
+
saved = [str(candidates[0].save(out))]
|
|
198
|
+
if args.save_all:
|
|
199
|
+
for i, c in enumerate(candidates[1:], 2):
|
|
200
|
+
saved.append(str(c.save(out.with_name(f"{out.stem}_{i}{out.suffix}"))))
|
|
201
|
+
if args.json:
|
|
202
|
+
_print_json({"saved": saved, "candidates": [c.to_dict() for c in candidates]})
|
|
203
|
+
return 0
|
|
204
|
+
for i, c in enumerate(candidates, 1):
|
|
205
|
+
print(
|
|
206
|
+
f" #{i} {c.start:8.2f}–{c.end:8.2f} s {c.duration:5.1f} s score {c.score:.2f} "
|
|
207
|
+
f"SNR {c.snr_db:4.1f} dB speech {c.speech_ratio:.0%}"
|
|
208
|
+
+ (f" clipping {c.clipping:.2%}" if c.clipping else "")
|
|
209
|
+
)
|
|
210
|
+
print(f"→ {saved[0]}" + (f" + {out.with_suffix('.txt').name}" if candidates[0].text else ""))
|
|
211
|
+
return 0
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# ---------- parser ----------
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
218
|
+
parser = argparse.ArgumentParser(
|
|
219
|
+
prog="voxprep",
|
|
220
|
+
description="Turn any audio/video into model-ready input for any AI, "
|
|
221
|
+
"then stitch the results back to the original timeline.",
|
|
222
|
+
)
|
|
223
|
+
parser.add_argument("--version", action="version", version=f"voxprep {__version__}")
|
|
224
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
225
|
+
|
|
226
|
+
def common(p, vad=True):
|
|
227
|
+
p.add_argument("--json", action="store_true", help="machine-readable output")
|
|
228
|
+
if vad:
|
|
229
|
+
p.add_argument("--vad", default="auto", choices=["auto", "silero", "energy"])
|
|
230
|
+
|
|
231
|
+
p = sub.add_parser("inspect", help="health check a file and show which models can take it")
|
|
232
|
+
p.add_argument("file")
|
|
233
|
+
common(p)
|
|
234
|
+
p.set_defaults(func=cmd_inspect)
|
|
235
|
+
|
|
236
|
+
p = sub.add_parser("presets", help="list model presets and their limits")
|
|
237
|
+
common(p, vad=False)
|
|
238
|
+
p.set_defaults(func=cmd_presets)
|
|
239
|
+
|
|
240
|
+
p = sub.add_parser("prepare", help="re-encode / split a file for a model, with a manifest")
|
|
241
|
+
p.add_argument("file")
|
|
242
|
+
p.add_argument("--for", dest="target", default="openai", help="preset name, or 'custom'")
|
|
243
|
+
p.add_argument("-o", "--output", help="output folder (default: <name>_<preset>)")
|
|
244
|
+
p.add_argument(
|
|
245
|
+
"--strip-silence", action="store_true", help="remove long pauses (timestamps kept)"
|
|
246
|
+
)
|
|
247
|
+
p.add_argument("--max-mb", type=float, help="size limit per chunk (any model)")
|
|
248
|
+
p.add_argument("--max-sec", type=float, help="duration limit per chunk (any model)")
|
|
249
|
+
p.add_argument("--rate", type=int, help="sample rate")
|
|
250
|
+
p.add_argument("--format", choices=["wav", "flac", "mp3", "opus"])
|
|
251
|
+
p.add_argument("--bitrate", type=int, help="bits per second for mp3 / opus")
|
|
252
|
+
common(p)
|
|
253
|
+
p.set_defaults(func=cmd_prepare)
|
|
254
|
+
|
|
255
|
+
p = sub.add_parser("stitch", help="merge per-chunk results back onto the original timeline")
|
|
256
|
+
p.add_argument("manifest", help="manifest.json from `prepare`, or its folder")
|
|
257
|
+
p.add_argument(
|
|
258
|
+
"results", nargs="*", help="one result per chunk, or a folder (default: chunk_NNN.*)"
|
|
259
|
+
)
|
|
260
|
+
p.add_argument("-o", "--output", help="output file; format from extension")
|
|
261
|
+
p.add_argument("-f", "--format", choices=OUTPUT_FORMATS)
|
|
262
|
+
p.add_argument("--no-refine", action="store_true", help="keep segments as returned")
|
|
263
|
+
common(p, vad=False)
|
|
264
|
+
p.set_defaults(func=cmd_stitch)
|
|
265
|
+
|
|
266
|
+
for name in ("subtitle", "transcribe"):
|
|
267
|
+
p = sub.add_parser(name, help="prepare → transcribe each chunk → stitch, in one go")
|
|
268
|
+
p.add_argument("file")
|
|
269
|
+
p.add_argument("--via", default="openai", choices=["openai", "groq", "funasr"])
|
|
270
|
+
p.add_argument("--model", help="model name for the backend")
|
|
271
|
+
p.add_argument("--language", help="language hint, e.g. en, zh")
|
|
272
|
+
p.add_argument("-o", "--output", help="output file (default: <name>.srt)")
|
|
273
|
+
p.add_argument("-f", "--format", choices=OUTPUT_FORMATS)
|
|
274
|
+
p.add_argument("--strip-silence", action="store_true")
|
|
275
|
+
p.add_argument("--no-refine", action="store_true", help="keep segments as returned")
|
|
276
|
+
common(p, vad=False)
|
|
277
|
+
p.set_defaults(func=cmd_subtitle)
|
|
278
|
+
|
|
279
|
+
p = sub.add_parser("ref-clip", help="extract the cleanest voice-clone reference clip")
|
|
280
|
+
p.add_argument("file")
|
|
281
|
+
p.add_argument("--for", dest="target", default="generic", choices=list(presets.CLONE))
|
|
282
|
+
p.add_argument("-o", "--output", help="output WAV (default: ref.wav)")
|
|
283
|
+
p.add_argument("--top", type=int, default=3, help="how many candidates to report")
|
|
284
|
+
p.add_argument("--save-all", action="store_true", help="also save runner-up clips")
|
|
285
|
+
p.add_argument("--min-sec", type=float)
|
|
286
|
+
p.add_argument("--max-sec", type=float)
|
|
287
|
+
p.add_argument("--via", choices=["openai", "groq", "funasr"], help="transcribe the clip too")
|
|
288
|
+
common(p)
|
|
289
|
+
p.set_defaults(func=cmd_ref_clip)
|
|
290
|
+
return parser
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def main(argv: list[str] | None = None) -> int:
|
|
294
|
+
for stream in (sys.stdout, sys.stderr):
|
|
295
|
+
if hasattr(stream, "reconfigure"):
|
|
296
|
+
stream.reconfigure(encoding="utf-8")
|
|
297
|
+
args = build_parser().parse_args(argv)
|
|
298
|
+
try:
|
|
299
|
+
return args.func(args)
|
|
300
|
+
except (FileNotFoundError, ValueError, KeyError, ImportError) as e:
|
|
301
|
+
print(f"voxprep: error: {e}", file=sys.stderr)
|
|
302
|
+
return 2
|
|
303
|
+
except Exception as e: # backend / network errors: one clean line unless debugging
|
|
304
|
+
if os.environ.get("VOXPREP_DEBUG"):
|
|
305
|
+
raise
|
|
306
|
+
print(f"voxprep: error: {type(e).__name__}: {e}", file=sys.stderr)
|
|
307
|
+
return 1
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
if __name__ == "__main__":
|
|
311
|
+
raise SystemExit(main())
|
voxprep/diagnose.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Health check of an audio/video file and whether each model can take it as is."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass, field
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from . import io, presets, vad
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Fit:
|
|
14
|
+
"""Whether a file can go to one model, and what voxprep would do about it."""
|
|
15
|
+
|
|
16
|
+
preset: str
|
|
17
|
+
action: str # "send" | "compress" | "split"
|
|
18
|
+
encoded_bytes: int
|
|
19
|
+
reason: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Report:
|
|
24
|
+
path: str | None
|
|
25
|
+
container: str
|
|
26
|
+
codec: str
|
|
27
|
+
sample_rate: int
|
|
28
|
+
channels: int
|
|
29
|
+
duration: float
|
|
30
|
+
size_bytes: int | None
|
|
31
|
+
has_video: bool
|
|
32
|
+
speech_seconds: float
|
|
33
|
+
silence_ratio: float
|
|
34
|
+
peak_dbfs: float
|
|
35
|
+
rms_dbfs: float
|
|
36
|
+
clipping_ratio: float
|
|
37
|
+
fits: list[Fit] = field(default_factory=list)
|
|
38
|
+
|
|
39
|
+
def to_dict(self) -> dict:
|
|
40
|
+
return asdict(self)
|
|
41
|
+
|
|
42
|
+
def summary(self) -> str:
|
|
43
|
+
lines = [
|
|
44
|
+
f"{self.path or '<bytes>'}",
|
|
45
|
+
f" {_hms(self.duration)} · {self.container}/{self.codec} · "
|
|
46
|
+
f"{self.sample_rate} Hz · {self.channels} ch"
|
|
47
|
+
+ (f" · {self.size_bytes / 1e6:.1f} MB" if self.size_bytes else "")
|
|
48
|
+
+ (" · has video" if self.has_video else ""),
|
|
49
|
+
f" speech {_hms(self.speech_seconds)} · silence {self.silence_ratio:.0%} · "
|
|
50
|
+
f"peak {self.peak_dbfs:.1f} dBFS · rms {self.rms_dbfs:.1f} dBFS"
|
|
51
|
+
+ (f" · clipping {self.clipping_ratio:.2%}" if self.clipping_ratio > 1e-4 else ""),
|
|
52
|
+
]
|
|
53
|
+
for f in self.fits:
|
|
54
|
+
mark = {"send": "✓", "compress": "~", "split": "✂"}[f.action]
|
|
55
|
+
lines.append(f" {mark} {f.preset:16s} {f.reason}")
|
|
56
|
+
return "\n".join(lines)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def inspect(source: io.Source, vad_backend: str = "auto") -> Report:
|
|
60
|
+
"""Decode ``source`` once and report format, loudness, silence and per-model fit."""
|
|
61
|
+
audio = io.load(source, sample_rate=vad.SAMPLE_RATE)
|
|
62
|
+
src = audio.source
|
|
63
|
+
assert src is not None
|
|
64
|
+
spans = vad.detect(audio, backend=vad_backend)
|
|
65
|
+
speech = sum(s.duration for s in spans)
|
|
66
|
+
x = audio.samples
|
|
67
|
+
peak = float(np.max(np.abs(x))) if len(x) else 0.0
|
|
68
|
+
rms = float(np.sqrt(np.mean(x**2))) if len(x) else 0.0
|
|
69
|
+
|
|
70
|
+
report = Report(
|
|
71
|
+
path=src.path,
|
|
72
|
+
container=src.container,
|
|
73
|
+
codec=src.codec,
|
|
74
|
+
sample_rate=src.sample_rate,
|
|
75
|
+
channels=src.channels,
|
|
76
|
+
duration=audio.duration,
|
|
77
|
+
size_bytes=src.size_bytes,
|
|
78
|
+
has_video=src.has_video,
|
|
79
|
+
speech_seconds=round(speech, 3),
|
|
80
|
+
silence_ratio=round(1 - speech / audio.duration, 4) if audio.duration else 0.0,
|
|
81
|
+
peak_dbfs=round(_dbfs(peak), 2),
|
|
82
|
+
rms_dbfs=round(_dbfs(rms), 2),
|
|
83
|
+
clipping_ratio=round(float(np.mean(np.abs(x) >= 0.999)), 6) if len(x) else 0.0,
|
|
84
|
+
)
|
|
85
|
+
for preset in presets.TRANSCRIBE.values():
|
|
86
|
+
report.fits.append(fit(report, preset))
|
|
87
|
+
return report
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def fit(report: Report, preset: presets.TranscribePreset) -> Fit:
|
|
91
|
+
"""Decide whether the file goes as is, after re-encoding, or split into chunks."""
|
|
92
|
+
est = io.estimate_size(report.duration, preset.fmt, preset.sample_rate, preset.bitrate)
|
|
93
|
+
over_time = preset.max_seconds is not None and report.duration > preset.max_seconds
|
|
94
|
+
over_size = preset.max_bytes is not None and est > preset.max_bytes
|
|
95
|
+
if over_time or over_size:
|
|
96
|
+
n_time = report.duration / preset.max_seconds if over_time else 1
|
|
97
|
+
n_size = est / preset.max_bytes if over_size else 1
|
|
98
|
+
n = int(np.ceil(max(n_time, n_size)))
|
|
99
|
+
why = (
|
|
100
|
+
"longer than " + _hms(preset.max_seconds)
|
|
101
|
+
if over_time
|
|
102
|
+
else (f"~{est / 1e6:.1f} MB as {preset.fmt}, limit {preset.max_bytes / 1e6:.0f} MB")
|
|
103
|
+
)
|
|
104
|
+
return Fit(preset.name, "split", est, f"{why} → ~{n} chunks at pauses")
|
|
105
|
+
original_ok = (
|
|
106
|
+
report.size_bytes is not None
|
|
107
|
+
and (preset.max_bytes is None or report.size_bytes <= preset.max_bytes)
|
|
108
|
+
and not report.has_video
|
|
109
|
+
)
|
|
110
|
+
if original_ok:
|
|
111
|
+
return Fit(preset.name, "send", report.size_bytes or est, "fits as is")
|
|
112
|
+
return Fit(
|
|
113
|
+
preset.name,
|
|
114
|
+
"compress",
|
|
115
|
+
est,
|
|
116
|
+
f"fits after re-encoding to {preset.fmt} (~{est / 1e6:.1f} MB)",
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _dbfs(v: float) -> float:
|
|
121
|
+
return 20 * np.log10(v) if v > 0 else -120.0
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _hms(seconds: float | None) -> str:
|
|
125
|
+
if seconds is None:
|
|
126
|
+
return "-"
|
|
127
|
+
s = int(round(seconds))
|
|
128
|
+
h, rem = divmod(s, 3600)
|
|
129
|
+
m, s = divmod(rem, 60)
|
|
130
|
+
return f"{h}h{m:02d}m{s:02d}s" if h else f"{m}m{s:02d}s"
|
voxprep/io.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Decode any audio/video into mono float32 PCM, and encode PCM back to files or bytes.
|
|
2
|
+
|
|
3
|
+
Built on PyAV, whose wheels bundle FFmpeg, so no system FFmpeg install is needed.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import io as _io
|
|
9
|
+
import os
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import av
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
PathLike = str | os.PathLike[str]
|
|
17
|
+
Source = PathLike | bytes | _io.IOBase
|
|
18
|
+
|
|
19
|
+
# Output formats we promise. Each maps to (container format, codec, file extension).
|
|
20
|
+
FORMATS: dict[str, tuple[str, str, str]] = {
|
|
21
|
+
"wav": ("wav", "pcm_s16le", ".wav"),
|
|
22
|
+
"flac": ("flac", "flac", ".flac"),
|
|
23
|
+
"mp3": ("mp3", "libmp3lame", ".mp3"),
|
|
24
|
+
"opus": ("ogg", "libopus", ".ogg"),
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
# libopus only accepts these sample rates.
|
|
28
|
+
_OPUS_RATES = (8000, 12000, 16000, 24000, 48000)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class Audio:
|
|
33
|
+
"""Mono float32 PCM in [-1, 1] plus the sample rate."""
|
|
34
|
+
|
|
35
|
+
samples: np.ndarray
|
|
36
|
+
sample_rate: int
|
|
37
|
+
source: SourceInfo | None = field(default=None, repr=False)
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def duration(self) -> float:
|
|
41
|
+
return len(self.samples) / self.sample_rate
|
|
42
|
+
|
|
43
|
+
def slice(self, start: float, end: float) -> Audio:
|
|
44
|
+
"""Return the part between ``start`` and ``end`` seconds."""
|
|
45
|
+
a = max(0, int(round(start * self.sample_rate)))
|
|
46
|
+
b = min(len(self.samples), int(round(end * self.sample_rate)))
|
|
47
|
+
return Audio(self.samples[a:b], self.sample_rate, self.source)
|
|
48
|
+
|
|
49
|
+
def resample(self, sample_rate: int) -> Audio:
|
|
50
|
+
if sample_rate == self.sample_rate:
|
|
51
|
+
return self
|
|
52
|
+
return Audio(
|
|
53
|
+
_resample(self.samples, self.sample_rate, sample_rate), sample_rate, self.source
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
def save(self, path: PathLike, fmt: str | None = None, bitrate: int | None = None) -> Path:
|
|
57
|
+
path = Path(path)
|
|
58
|
+
fmt = fmt or _format_from_ext(path.suffix)
|
|
59
|
+
path.write_bytes(encode(self, fmt, bitrate))
|
|
60
|
+
return path
|
|
61
|
+
|
|
62
|
+
def to_bytes(self, fmt: str = "wav", bitrate: int | None = None) -> bytes:
|
|
63
|
+
return encode(self, fmt, bitrate)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class SourceInfo:
|
|
68
|
+
"""What the original file looked like before decoding."""
|
|
69
|
+
|
|
70
|
+
path: str | None
|
|
71
|
+
container: str
|
|
72
|
+
codec: str
|
|
73
|
+
sample_rate: int
|
|
74
|
+
channels: int
|
|
75
|
+
duration: float
|
|
76
|
+
size_bytes: int | None
|
|
77
|
+
bit_rate: int | None
|
|
78
|
+
has_video: bool
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _open(source: Source) -> tuple[av.container.InputContainer, str | None, int | None]:
|
|
82
|
+
if isinstance(source, bytes):
|
|
83
|
+
return av.open(_io.BytesIO(source)), None, len(source)
|
|
84
|
+
if isinstance(source, _io.IOBase):
|
|
85
|
+
return av.open(source), None, None
|
|
86
|
+
path = os.fspath(source)
|
|
87
|
+
if not os.path.exists(path):
|
|
88
|
+
raise FileNotFoundError(path)
|
|
89
|
+
return av.open(path), path, os.path.getsize(path)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def probe(source: Source) -> SourceInfo:
|
|
93
|
+
"""Read container metadata without decoding the whole file."""
|
|
94
|
+
container, path, size = _open(source)
|
|
95
|
+
with container:
|
|
96
|
+
stream = _audio_stream(container)
|
|
97
|
+
duration = _stream_duration(container, stream)
|
|
98
|
+
return SourceInfo(
|
|
99
|
+
path=path,
|
|
100
|
+
container=container.format.name,
|
|
101
|
+
codec=stream.codec_context.name,
|
|
102
|
+
sample_rate=stream.codec_context.sample_rate,
|
|
103
|
+
channels=stream.codec_context.channels,
|
|
104
|
+
duration=duration,
|
|
105
|
+
size_bytes=size,
|
|
106
|
+
bit_rate=container.bit_rate or stream.bit_rate,
|
|
107
|
+
has_video=any(s.type == "video" for s in container.streams),
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def load(source: Source, sample_rate: int = 16000) -> Audio:
|
|
112
|
+
"""Decode the first audio stream of any audio/video file to mono float32 at ``sample_rate``."""
|
|
113
|
+
container, path, size = _open(source)
|
|
114
|
+
with container:
|
|
115
|
+
stream = _audio_stream(container)
|
|
116
|
+
info = SourceInfo(
|
|
117
|
+
path=path,
|
|
118
|
+
container=container.format.name,
|
|
119
|
+
codec=stream.codec_context.name,
|
|
120
|
+
sample_rate=stream.codec_context.sample_rate,
|
|
121
|
+
channels=stream.codec_context.channels,
|
|
122
|
+
duration=_stream_duration(container, stream),
|
|
123
|
+
size_bytes=size,
|
|
124
|
+
bit_rate=container.bit_rate or stream.bit_rate,
|
|
125
|
+
has_video=any(s.type == "video" for s in container.streams),
|
|
126
|
+
)
|
|
127
|
+
resampler = av.AudioResampler(format="flt", layout="mono", rate=sample_rate)
|
|
128
|
+
parts: list[np.ndarray] = []
|
|
129
|
+
for frame in container.decode(stream):
|
|
130
|
+
for out in resampler.resample(frame):
|
|
131
|
+
parts.append(out.to_ndarray().reshape(-1))
|
|
132
|
+
for out in resampler.resample(None):
|
|
133
|
+
parts.append(out.to_ndarray().reshape(-1))
|
|
134
|
+
samples = np.concatenate(parts).astype(np.float32) if parts else np.zeros(0, np.float32)
|
|
135
|
+
if info.duration <= 0:
|
|
136
|
+
info.duration = len(samples) / sample_rate
|
|
137
|
+
return Audio(samples, sample_rate, info)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def encode(audio: Audio, fmt: str = "wav", bitrate: int | None = None) -> bytes:
|
|
141
|
+
"""Encode mono PCM to ``wav`` / ``flac`` / ``mp3`` / ``opus`` bytes."""
|
|
142
|
+
if fmt not in FORMATS:
|
|
143
|
+
raise ValueError(f"unsupported format {fmt!r}; choose from {sorted(FORMATS)}")
|
|
144
|
+
container_fmt, codec, _ = FORMATS[fmt]
|
|
145
|
+
if codec == "libopus" and audio.sample_rate not in _OPUS_RATES:
|
|
146
|
+
target = min(_OPUS_RATES, key=lambda r: (r < audio.sample_rate, abs(r - audio.sample_rate)))
|
|
147
|
+
audio = audio.resample(target)
|
|
148
|
+
rate = audio.sample_rate
|
|
149
|
+
|
|
150
|
+
buf = _io.BytesIO()
|
|
151
|
+
with av.open(buf, mode="w", format=container_fmt) as out:
|
|
152
|
+
stream = out.add_stream(codec, rate=rate, layout="mono")
|
|
153
|
+
bitrate = bitrate or default_bitrate(fmt)
|
|
154
|
+
if bitrate:
|
|
155
|
+
stream.bit_rate = bitrate
|
|
156
|
+
sample_fmt = stream.codec_context.format.name
|
|
157
|
+
pcm = np.clip(audio.samples, -1.0, 1.0)
|
|
158
|
+
frame_size = stream.codec_context.frame_size or 4096
|
|
159
|
+
resampler = av.AudioResampler(format=sample_fmt, layout="mono", rate=rate)
|
|
160
|
+
pts = 0
|
|
161
|
+
for i in range(0, len(pcm), frame_size):
|
|
162
|
+
block = np.ascontiguousarray(pcm[i : i + frame_size].reshape(1, -1), dtype=np.float32)
|
|
163
|
+
frame = av.AudioFrame.from_ndarray(block, format="flt", layout="mono")
|
|
164
|
+
frame.sample_rate = rate
|
|
165
|
+
frame.pts = pts
|
|
166
|
+
pts += block.shape[1]
|
|
167
|
+
for f in resampler.resample(frame):
|
|
168
|
+
for packet in stream.encode(f):
|
|
169
|
+
out.mux(packet)
|
|
170
|
+
for f in resampler.resample(None):
|
|
171
|
+
for packet in stream.encode(f):
|
|
172
|
+
out.mux(packet)
|
|
173
|
+
for packet in stream.encode(None):
|
|
174
|
+
out.mux(packet)
|
|
175
|
+
return buf.getvalue()
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def estimate_size(duration: float, fmt: str, sample_rate: int, bitrate: int | None) -> int:
|
|
179
|
+
"""Rough encoded size in bytes, used to plan chunks before encoding."""
|
|
180
|
+
if fmt == "wav":
|
|
181
|
+
return int(duration * sample_rate * 2) + 44
|
|
182
|
+
if fmt == "flac":
|
|
183
|
+
return int(duration * sample_rate * 2 * 0.6) + 8192 # speech typically ~55-65% of PCM16
|
|
184
|
+
bps = bitrate or default_bitrate(fmt)
|
|
185
|
+
return int(duration * bps / 8 * 1.03) + 4096 # ~3% container overhead
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def default_bitrate(fmt: str) -> int | None:
|
|
189
|
+
return {"mp3": 48_000, "opus": 32_000}.get(fmt)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _resample(samples: np.ndarray, src: int, dst: int) -> np.ndarray:
|
|
193
|
+
"""Resample mono float32 with FFmpeg's swresample via PyAV."""
|
|
194
|
+
resampler = av.AudioResampler(format="flt", layout="mono", rate=dst)
|
|
195
|
+
frame = av.AudioFrame.from_ndarray(
|
|
196
|
+
np.ascontiguousarray(samples.reshape(1, -1), dtype=np.float32), format="flt", layout="mono"
|
|
197
|
+
)
|
|
198
|
+
frame.sample_rate = src
|
|
199
|
+
frame.pts = 0
|
|
200
|
+
parts = [f.to_ndarray().reshape(-1) for f in resampler.resample(frame)]
|
|
201
|
+
parts += [f.to_ndarray().reshape(-1) for f in resampler.resample(None)]
|
|
202
|
+
return np.concatenate(parts).astype(np.float32) if parts else np.zeros(0, np.float32)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _audio_stream(container: av.container.InputContainer) -> av.audio.stream.AudioStream:
|
|
206
|
+
if not container.streams.audio:
|
|
207
|
+
raise ValueError("no audio stream found")
|
|
208
|
+
return container.streams.audio[0]
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _stream_duration(container, stream) -> float:
|
|
212
|
+
if stream.duration is not None and stream.time_base is not None:
|
|
213
|
+
return float(stream.duration * stream.time_base)
|
|
214
|
+
if container.duration is not None:
|
|
215
|
+
return container.duration / av.time_base
|
|
216
|
+
return 0.0
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _format_from_ext(ext: str) -> str:
|
|
220
|
+
ext = ext.lower()
|
|
221
|
+
for name, (_, _, e) in FORMATS.items():
|
|
222
|
+
if e == ext:
|
|
223
|
+
return name
|
|
224
|
+
if ext == ".opus":
|
|
225
|
+
return "opus"
|
|
226
|
+
raise ValueError(f"can't infer format from extension {ext!r}; pass fmt=")
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2020-present Silero Team
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
File without changes
|
|
Binary file
|