Text-to-Speech
Pocket-TTS
Safetensors
Thai
thai
voice-cloning
File size: 3,484 Bytes
97cf942
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()