"""CTEngine: the Pocket TTS (CALM) Thai voice-cloning core of MrJMThaiTTS_CT. A thin wrapper around the kyutai/pocket-tts API. A reference clip is encoded into a ModelState (speaker, style and prosody), and the model speaks in that voice. from engine.engine import CTEngine eng = CTEngine(config="thai.resolved.yaml", quantize=True) # CPU by default voice = eng.clone("speaker.wav") # zero-shot clone audio = eng.synthesize(phoneme_text, voice) # float32 mono 24 kHz eng.save_voice(voice, "voices/speaker.safetensors") Copyright (c) 2026 FireH2O. All rights reserved. See CODE_LICENSE. """ from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Optional, Union import numpy as np AudioSource = Union[str, Path, np.ndarray] @dataclass class VoicePack: """A conditioned voice: a Pocket TTS ModelState plus where it lives on disk. state : the ModelState returned by get_state_for_audio_prompt() path : optional .safetensors path (fast reload), set after save_voice() """ state: object path: Optional[Path] = None class CTEngine: def __init__( self, config: Optional[str] = None, language: Optional[str] = None, checkpoint: Optional[str] = None, quantize: bool = True, device: str = "cpu", ): from pocket_tts import TTSModel kwargs: dict = {"quantize": quantize} if config: kwargs["config"] = config elif language: kwargs["language"] = language if checkpoint: kwargs["checkpoint"] = checkpoint self._torch = __import__("torch") self.model = TTSModel.load_model(**kwargs) self.device = device if device == "cuda" and self._torch.cuda.is_available(): self.model.to(device) self.sample_rate = int(self.model.sample_rate) # ---- voice cloning ------------------------------------------------- def clone(self, ref: AudioSource, truncate: bool = False) -> VoicePack: """Encode a reference clip (path / URL / tensor) into a voice.""" state = self.model.get_state_for_audio_prompt(ref, truncate=truncate) return VoicePack(state=state) def load_voice(self, path: Union[str, Path]) -> VoicePack: """Fast-reload a saved .safetensors voice pack.""" state = self.model.get_state_for_audio_prompt(str(path)) return VoicePack(state=state, path=Path(path)) def save_voice(self, voice: VoicePack, path: Union[str, Path]) -> Path: from pocket_tts import export_model_state p = Path(path) p.parent.mkdir(parents=True, exist_ok=True) export_model_state(voice.state, str(p)) voice.path = p return p # ---- synthesis ----------------------------------------------------- def synthesize(self, text: str, voice: VoicePack, frames_after_eos: int = 2) -> np.ndarray: """Generate float32 mono audio at self.sample_rate.""" audio = self.model.generate_audio( model_state=voice.state, text_to_generate=text, frames_after_eos=frames_after_eos, copy_state=True, ) t = self._torch.as_tensor(audio).detach().float() if t.dim() == 2: # [channels, samples] -> mono t = t.mean(dim=0) return t.cpu().numpy()