File size: 4,934 Bytes
cefb829 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | # Copyright 2026 Core Epoch LLC
# Licensed under the Apache License, Version 2.0 (see LICENSE and NOTICE).
"""Check single-model accuracy (Whisper base.en WER across 34 sentences x 2 voices = 68 clips)
and 10-run latency for the Kenosis INT8 tiny-voca ONNX models on ONNX Runtime or OpenVINO.
Usage:
python eval_tts.py [ort|openvino] [model.onnx] [threads] [--dizione]
Deps:
pip install onnxruntime openvino numpy soundfile scipy faster-whisper openai-whisper
"""
from __future__ import annotations
import json
import math
import statistics
import sys
import time
from pathlib import Path
import numpy as np
from faster_whisper import WhisperModel
from scipy.signal import resample_poly
from whisper.normalizers import EnglishTextNormalizer
from run_tts import build_feed
HERE = Path(__file__).resolve().parent
FULL_LINE = "The northern gate is locked, Commander. Take the underground pass, and meet me at the extraction point."
def edits(ref: list[str], hyp: list[str]) -> int:
prev = list(range(len(hyp) + 1))
for i, r in enumerate(ref, 1):
cur = [i] + [0] * len(hyp)
for j, h in enumerate(hyp, 1):
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (r != h))
prev = cur
return prev[-1]
def to_16k(wav: np.ndarray) -> np.ndarray:
g = math.gcd(24000, 16000)
return resample_poly(wav.astype(np.float32), 16000 // g, 24000 // g).astype(np.float32)
def make_runner(backend: str, model_path: Path, threads: int):
if backend == "ort":
import onnxruntime as ort
so = ort.SessionOptions()
so.intra_op_num_threads = threads
so.inter_op_num_threads = 1
so.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
so.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
sess = ort.InferenceSession(str(model_path), so, providers=["CPUExecutionProvider"])
return lambda feed: np.asarray(sess.run(["audio"], feed)[0], dtype=np.float32).reshape(-1)
if backend == "openvino":
import openvino as ov
core = ov.Core()
compiled = core.compile_model(
core.read_model(str(model_path)),
"CPU",
{"INFERENCE_NUM_THREADS": str(threads), "NUM_STREAMS": "1"},
)
req = compiled.create_infer_request()
out = compiled.outputs[0]
return lambda feed: np.asarray(req.infer(feed)[out], dtype=np.float32).reshape(-1)
raise ValueError(f"Unknown backend {backend!r}; choose ort or openvino")
def main() -> None:
raw_args = [a for a in sys.argv[1:] if a != "--dizione"]
use_dizione = "--dizione" in sys.argv[1:]
backend = raw_args[0].lower() if len(raw_args) > 0 else "ort"
default_model = "tiny_voca_int8_kenosis.onnx" if backend == "ort" else "tiny_voca_w8_kenosis.onnx"
model_path = Path(raw_args[1]) if len(raw_args) > 1 else (HERE / default_model)
threads = int(raw_args[2]) if len(raw_args) > 2 else 4
sentences: list[str] = json.loads((HERE / "eval_sentences.json").read_text(encoding="utf-8"))
run_model = make_runner(backend, model_path, threads)
judge = WhisperModel("base.en", device="cpu", compute_type="float32", cpu_threads=4)
norm = EnglishTextNormalizer()
total_we = total_wn = 0
for voice in ("F2", "M2"):
we = wn = 0
for sent in sentences:
wav = run_model(build_feed(sent, voice=voice, use_dizione=use_dizione))
pk = float(np.max(np.abs(wav))) if wav.size else 0.0
if pk > 0.99:
wav = wav * (0.99 / pk)
segs, _ = judge.transcribe(
to_16k(wav),
language="en",
beam_size=5,
temperature=0.0,
condition_on_previous_text=False,
vad_filter=False,
without_timestamps=True,
)
hyp = " ".join(s.text.strip() for s in segs).strip()
rn, hn = norm(sent), norm(hyp)
we += edits(rn.split(), hn.split())
wn += len(rn.split())
total_we += we
total_wn += wn
print(f"{voice} ({len(sentences)} sentences): WER {we / wn * 100:.2f}% ({we}/{wn})")
print(f"Combined ({len(sentences) * 2} utterances): WER {total_we / total_wn * 100:.2f}% ({total_we}/{total_wn})")
feed_full = build_feed(FULL_LINE, voice="F2", use_dizione=use_dizione)
for _ in range(2):
run_model(feed_full)
ms_list = []
durs = []
for _ in range(10):
t0 = time.perf_counter()
wav = run_model(feed_full)
ms_list.append((time.perf_counter() - t0) * 1000.0)
durs.append(float(wav.size) / 24000.0)
med_ms = statistics.median(ms_list)
med_s = statistics.median(durs)
print(f"Speed ({backend}, {threads}t, 10 runs): median {med_ms:.2f} ms for {med_s:.2f}s audio ({med_s / (med_ms / 1000.0):.1f}x real time)")
if __name__ == "__main__":
main()
|