Text-to-Speech
Pocket-TTS
Safetensors
Thai
thai
voice-cloning
FireH2O's picture
MrJMThaiTTS_CT: Thai voice-cloning TTS for CPU (model, run code, scores)
97cf942 verified
Raw History Blame Contribute Delete
4.37 kB
"""MrJMThaiTTS_CT: Thai text-to-speech in the voice of a short reference clip, on a CPU.
python ct.py "สวัสดีครับ วันนี้อากาศดี" --voice voices/som_ref.wav -o hello.wav
python ct.py -f article.txt --voice speaker.wav -o out.wav
python ct.py "ราคา 1,250 บาท" --voice voices/saved/speaker.safetensors -o out.wav
The Thai front-end runs first and turns the text into phonemes (frontend/modeltext.py): the model reads
phonemes, not Thai script. Then the Pocket TTS (CALM) core speaks them in the voice of the reference clip.
Only clone a voice with the speaker's explicit consent.
Copyright (c) 2026 FireH2O. All rights reserved. See CODE_LICENSE.
"""
from __future__ import annotations
import argparse
import sys
import time
import wave
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
from frontend.modeltext import to_model_text # noqa: E402
from frontend.normalize import ThaiFrontend # noqa: E402
HERE = Path(__file__).resolve().parent
DEFAULTS = dict(
config=str(HERE / "thai.yaml"),
quantize=True,
device="cpu",
gap_ms=200,
max_chars=160,
)
def resolved_config(config: str | None = None) -> str:
"""The config with weights_path and tokenizer_path as full paths next to it (the library needs them)."""
import tempfile
import yaml
src = Path(config or DEFAULTS["config"]).resolve()
cfg = yaml.safe_load(src.read_text("utf-8"))
cfg["weights_path"] = str((src.parent / cfg["weights_path"]).resolve())
table = cfg["flow_lm"]["lookup_table"]
table["tokenizer_path"] = str((src.parent / table["tokenizer_path"]).resolve())
out = Path(tempfile.gettempdir()) / "mrjmthaitts_ct.resolved.yaml"
out.write_text(yaml.safe_dump(cfg, allow_unicode=True, sort_keys=False), "utf-8")
return str(out)
def _write_wav(path: Path, audio: np.ndarray, sr: int) -> None:
a16 = (np.clip(audio, -1.0, 1.0) * 32767).astype(np.int16)
with wave.open(str(path), "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(sr)
wf.writeframes(a16.tobytes())
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("text", nargs="?", help="text to synthesize")
ap.add_argument("-f", "--file", help="read text from a file instead")
ap.add_argument("--voice", required=True,
help="reference audio (.wav) or a voice saved by voices/voicepack.py (.safetensors)")
ap.add_argument("-o", "--output", default="out.wav")
ap.add_argument("--config", default=DEFAULTS["config"])
ap.add_argument("--device", default=DEFAULTS["device"], choices=["cpu", "cuda"])
ap.add_argument("--no-quantize", action="store_true", help="disable int8 (larger/slower, fp32)")
ap.add_argument("--gap-ms", type=int, default=DEFAULTS["gap_ms"])
ap.add_argument("--max-chars", type=int, default=DEFAULTS["max_chars"])
args = ap.parse_args()
text = args.text
if args.file:
text = Path(args.file).read_text(encoding="utf-8")
if not text:
ap.error("give text or -f FILE")
if not Path(args.voice).is_file():
ap.error(f"--voice: no such file: {args.voice}")
from engine.engine import CTEngine
fe = ThaiFrontend()
t0 = time.perf_counter()
eng = CTEngine(config=resolved_config(args.config), quantize=not args.no_quantize, device=args.device)
voice = eng.load_voice(args.voice) if args.voice.endswith(".safetensors") else eng.clone(args.voice)
load_t = time.perf_counter() - t0
chunks = fe.chunk_sentences(text, args.max_chars)
gap = np.zeros(int(eng.sample_rate * args.gap_ms / 1000), dtype=np.float32)
parts = []
t0 = time.perf_counter()
for c in chunks:
parts.append(eng.synthesize(to_model_text(fe, c), voice))
parts.append(gap)
synth_t = time.perf_counter() - t0
audio = np.concatenate(parts[:-1]) if parts else np.array([], dtype=np.float32)
_write_wav(Path(args.output), audio, eng.sample_rate)
dur = audio.size / eng.sample_rate
print(f"saved {args.output} audio={dur:.2f}s load={load_t:.1f}s synth={synth_t:.2f}s RTF={synth_t / dur:.3f}")
return 0
if __name__ == "__main__":
sys.exit(main())