#!/usr/bin/env python3 """Kokoro-82M: a text file in, a 16-bit mono WAV at the model's native rate out. Run by scripts/tts.mjs (the wrapper every TTS engine runs behind), with the python of the venv `archilyzer tts setup` built (kokoro-onnx 0.6.1 on onnxruntime, CPU). The wrapper resamples to 48 kHz and moves the file into place; this script only synthesizes. Stock voices only: --voice names one of the voices in voices-v1.0.bin. The language follows the voice's prefix: `b*` is British English (en-gb), every other voice American (en-us). On stdout, one JSON line: {sampleRate, seconds, loadSeconds, synthSeconds, lang}. Errors go to stderr with a non-zero exit. """ import argparse import json import sys import time import wave def main() -> int: p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) p.add_argument("--model", required=True, help="kokoro-v1.0.onnx") p.add_argument("--voices", required=True, help="voices-v1.0.bin") p.add_argument("--voice", default="af_heart") p.add_argument("--speed", type=float, default=1.0) p.add_argument("--lang", default=None, help="default: en-gb for b* voices, else en-us") p.add_argument("--output", required=False, help="the WAV to write") p.add_argument("--list-voices", action="store_true", help="print the voices file's names and exit") p.add_argument("text_file", nargs="?") args = p.parse_args() t0 = time.perf_counter() import numpy as np from kokoro_onnx import Kokoro kokoro = Kokoro(args.model, args.voices) load = time.perf_counter() - t0 if args.list_voices: print(json.dumps(sorted(kokoro.get_voices()))) return 0 if not args.output or not args.text_file: print("tts_kokoro: --output and a text file are required", file=sys.stderr) return 2 if args.voice not in kokoro.get_voices(): print(f"tts_kokoro: no voice {args.voice!r} in {args.voices}", file=sys.stderr) return 2 with open(args.text_file, encoding="utf-8") as f: text = f.read().strip() if not text: print("tts_kokoro: the text is empty", file=sys.stderr) return 2 lang = args.lang or ("en-gb" if args.voice.startswith("b") else "en-us") t1 = time.perf_counter() samples, rate = kokoro.create(text, voice=args.voice, speed=args.speed, lang=lang) synth = time.perf_counter() - t1 audio = np.clip(np.asarray(samples, dtype=np.float32).squeeze(), -1.0, 1.0) pcm = (audio * 32767.0).astype("