tiny-voca-int8-onnx / run_tts.py
ccoomler's picture
Initial release: Kenosis INT8 ONNX derivatives of n4ze3m/tiny-voca (7.74 MB / 7.73 MB)
cefb829 verified
Raw History Blame Contribute Delete
6.02 kB
# Copyright 2026 Core Epoch LLC
# Licensed under the Apache License, Version 2.0 (see LICENSE and NOTICE).
"""Synthesize 24 kHz English speech with the Kenosis INT8 tiny-voca ONNX models.
Usage:
python run_tts.py "Hello! This is a fast offline voice running on your processor." out.wav [F2|M2] [ort|openvino] [threads]
Deps:
pip install onnxruntime numpy soundfile # for ort (default)
pip install openvino numpy soundfile # for openvino
pip install git+https://github.com/n4ze3m/dizione # optional: full G2P for out-of-lexicon words
"""
from __future__ import annotations
import json
import os
import re
import sys
import time
from pathlib import Path
import numpy as np
import soundfile as sf
HERE = Path(__file__).resolve().parent
TOKEN_RE = re.compile(r"[A-Za-z]+(?:'[A-Za-z]+)*|[,.\?!;:\"'()—…]")
VOICES = {"F2": 0, "M2": 1}
def phonemize(text: str, repo_dir: Path = HERE, use_dizione: bool = True) -> tuple[list[int], list[int]]:
"""Convert English text into (tokens, stress) arrays matching n4ze3m/tiny-voca."""
if use_dizione:
try:
os.environ.setdefault("DIZIONE_DATA", str(repo_dir / "phonemizer"))
import dizione # type: ignore
phones = dizione.phonemize(text)
return list(phones.ids), list(phones.stress)
except ImportError:
pass
cfg = json.loads((repo_dir / "config.json").read_text(encoding="utf-8"))
vocab: dict[str, int] = cfg["vocab"]
lex: dict[str, list[str]] = {}
with open(repo_dir / "phonemizer" / "lexicon.tsv", encoding="utf-8") as fh:
for line in fh:
w, phs = line.rstrip("\r\n").split("\t", 1)
lex[w.lower()] = phs.split(" ")
norm_text = text.replace("...", "…").replace("--", "—")
tokens = [vocab["<bos>"]]
stress = [0]
prev_was_word = False
prev_was_punct = False
for part in TOKEN_RE.findall(norm_text):
if part in vocab and not part[0].isalpha():
tokens.append(vocab[part])
stress.append(0)
prev_was_word = False
prev_was_punct = True
continue
if prev_was_word or prev_was_punct:
tokens.append(vocab["<sp>"])
stress.append(0)
word = part.lower()
phs = lex.get(word)
if phs is None and word.endswith("'s") and word[:-2] in lex:
phs = lex[word[:-2]] + ["z"]
if phs is None:
tokens.append(vocab["<unk>"])
stress.append(0)
prev_was_word = True
prev_was_punct = False
continue
for ph in phs:
if ph.startswith("ˈ"):
st, sym = 1, ph[1:]
elif ph.startswith("ˌ"):
st, sym = 2, ph[1:]
else:
st, sym = 0, ph
tokens.append(vocab[sym])
stress.append(st)
prev_was_word = True
prev_was_punct = False
tokens.append(vocab["<eos>"])
stress.append(0)
return tokens, stress
def build_feed(
text: str, voice: str = "F2", speed: float = 1.0, repo_dir: Path = HERE, use_dizione: bool = True
) -> dict[str, np.ndarray]:
tokens, stress = phonemize(text, repo_dir=repo_dir, use_dizione=use_dizione)
return {
"tokens": np.array([tokens], dtype=np.int64),
"stress": np.array([stress], dtype=np.int64),
"voice": np.array([VOICES[voice.upper()]], dtype=np.int64),
"speed": np.array([speed], dtype=np.float32),
"pitch_shift": np.array([0.0], dtype=np.float32),
"pitch_range": np.array([1.0], dtype=np.float32),
}
def main() -> None:
if len(sys.argv) < 3:
print('Usage: python run_tts.py "Your text here." out.wav [F2|M2] [ort|openvino] [threads]')
sys.exit(2)
text = sys.argv[1]
out_wav = Path(sys.argv[2])
voice = sys.argv[3].upper() if len(sys.argv) > 3 else "F2"
backend = sys.argv[4].lower() if len(sys.argv) > 4 else "ort"
threads = int(sys.argv[5]) if len(sys.argv) > 5 else 4
if voice not in VOICES:
raise ValueError(f"Unknown voice {voice!r}; choose F2 or M2")
feed = build_feed(text, voice=voice)
if backend == "ort":
import onnxruntime as ort
model_path = HERE / "tiny_voca_int8_kenosis.onnx"
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"])
t0 = time.perf_counter()
audio = np.asarray(sess.run(["audio"], feed)[0], dtype=np.float32).reshape(-1)
elapsed_ms = (time.perf_counter() - t0) * 1000.0
elif backend == "openvino":
import openvino as ov
model_path = HERE / "tiny_voca_w8_kenosis.onnx"
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()
t0 = time.perf_counter()
res = req.infer(feed)
audio = np.asarray(res[compiled.outputs[0]], dtype=np.float32).reshape(-1)
elapsed_ms = (time.perf_counter() - t0) * 1000.0
else:
raise ValueError(f"Unknown backend {backend!r}; choose ort or openvino")
peak = float(np.max(np.abs(audio))) if audio.size else 0.0
if peak > 0.99:
audio = audio * (0.99 / peak)
sf.write(str(out_wav), audio, 24000)
dur_s = float(audio.size) / 24000.0
xrt = dur_s / (elapsed_ms / 1000.0) if elapsed_ms > 0 else 0.0
print(f"model: {model_path.name} backend: {backend} ({threads}t) voice: {voice}")
print(f"wrote: {out_wav} audio: {dur_s:.2f}s inference: {elapsed_ms:.1f} ms ({xrt:.1f}x real time)")
if __name__ == "__main__":
main()