PyThaiTTS

Open Source Thai Text-to-speech library in Python

class pythaitts.TTS(pretrained='fastthaig2p', mode='last_checkpoint', version='1.0', device: str = 'cpu', **kwargs)[source]
__init__(pretrained='fastthaig2p', mode='last_checkpoint', version='1.0', device: str = 'cpu', **kwargs) → None[source]
Parameters:
  • pretrained (str) – TTS pretrained (fastthaig2p, lunarlist_onnx, khanomtan, lunarlist, vachana)

  • mode (str) – pretrained mode (fastthaig2p, lunarlist_onnx, and vachana don’t support)

  • version (str) – model version (default is 1.0 or 1.1)

  • device (str) – device for running model. (fastthaig2p, lunarlist_onnx, and vachana support CPU only.)

Options for mode
  • last_checkpoint (default) - last checkpoint of model

  • best_model - Best model (best loss)

You can see more about khanomtan tts at https://github.com/wannaphong/KhanomTan-TTS-v1.0 and https://github.com/wannaphong/KhanomTan-TTS-v1.1 If you want to use khanomtan tts, you must to install coqui-tts before use the model by pip install coqui-tts.

For lunarlist tts model, you must to install nemo before use the model by pip install nemo_toolkit[‘tts’]. You can see more about lunarlist tts at https://link.medium.com/OpPjQis6wBb

For lunarlist_onnx tts model, You can see more about lunarlist tts at https://github.com/PyThaiNLP/thaitts-onnx

For vachana tts model, you must install vachanatts before using the model by pip install vachanatts. You can see more about vachana tts at https://github.com/VYNCX/VachanaTTS2

For fastthaig2p tts model, You can see more about fastthaig2p at https://github.com/awslabs/FastThaiG2P

load_pretrained(version='1.0', **kwargs)[source]

Load pretrained

tts(text: str, speaker_idx: str = 'thai_som', language_idx: str = 'th-th', return_type: str = 'file', filename: str = None, preprocess: bool = True, **kwargs)[source]

speech synthesis

Parameters:
  • text (str) – text

  • speaker_idx (str) – speaker (default is thai_som for fastthaig2p, Linda for khanomtan, th_f_1 for vachana)

  • language_idx (str) – language (default is th-th)

  • return_type (str) – return type (default is file)

  • filename (str) – path filename for save wav file if return_type is file.

  • preprocess (bool) – whether to preprocess text (convert numbers to Thai text and expand ๆ). Default is True.

  • kwargs – Additional parameters passed to the underlying model.

stream(text: str | Iterable[str], speaker_idx: str = 'thai_som', return_type: str = 'waveform', play: bool = False, preprocess: bool = True, max_phonemes: int = 400, **kwargs)[source]

Stream speech synthesis in real-time.

Parameters:
  • text (Union[str, Iterable[str]]) – Input text or stream of text tokens (e.g. from LLM)

  • speaker_idx (str) – Voice to use (default: “thai_som” for fastthaig2p)

  • return_type (str) – Return format (“waveform”, “bytes”, “raw”, “file”)

  • play (bool) – Whether to play audio chunks in real-time to speakers

  • preprocess (bool) – Whether to preprocess text (numbers to words, ๆ)

  • max_phonemes (int) – Maximum phonemes per synthesized chunk

  • kwargs – Additional parameters passed to the model

Returns:

Generator yielding audio chunks

tts_stream(text: str | Iterable[str], speaker_idx: str = 'thai_som', return_type: str = 'waveform', play: bool = False, preprocess: bool = True, max_phonemes: int = 400, **kwargs)

Stream speech synthesis in real-time.

Parameters:
  • text (Union[str, Iterable[str]]) – Input text or stream of text tokens (e.g. from LLM)

  • speaker_idx (str) – Voice to use (default: “thai_som” for fastthaig2p)

  • return_type (str) – Return format (“waveform”, “bytes”, “raw”, “file”)

  • play (bool) – Whether to play audio chunks in real-time to speakers

  • preprocess (bool) – Whether to preprocess text (numbers to words, ๆ)

  • max_phonemes (int) – Maximum phonemes per synthesized chunk

  • kwargs – Additional parameters passed to the model

Returns:

Generator yielding audio chunks

Real-time / Streaming TTS

PyThaiTTS provides real-time streaming speech synthesis and integration with RealtimeTTS.

class pythaitts.RealtimeTTS(pretrained: str = 'fastthaig2p', speaker_idx: str = 'thai_som', speed: float = 1.0, device: str = 'cpu', **kwargs)[source]

High-level Real-time Text-to-Speech manager for PyThaiTTS.

Supports streaming generation from text or token streams with low latency.

__init__(pretrained: str = 'fastthaig2p', speaker_idx: str = 'thai_som', speed: float = 1.0, device: str = 'cpu', **kwargs)[source]
stream(text: str | Iterable[str], speaker_idx: str | None = None, return_type: str = 'waveform', play: bool = False, preprocess: bool = True, max_phonemes: int = 400, **kwargs) → Iterator[ndarray | bytes | str][source]

Stream speech synthesis in real-time.

Parameters:
  • text (Union[str, Iterable[str]]) – Input text or token generator

  • speaker_idx (str) – Voice to use (default: initialized voice)

  • return_type (str) – Return format (“waveform”, “bytes”, “raw”, “file”)

  • play (bool) – Whether to play audio chunks in real-time

  • preprocess (bool) – Whether to preprocess text

  • max_phonemes (int) – Maximum phonemes per synthesized chunk

  • kwargs – Additional parameters passed to the model

Yield:

Audio chunk (numpy array, PCM bytes, or wav file path)

synthesize(text: str, **kwargs)[source]

Standard batch synthesis.

class pythaitts.FastThaiG2PEngine(voice: str | FastThaiG2PVoice = 'thai_som', speed: float = 1.0, model_path: str | Path | None = None, voicepack_path: str | Path | None = None, config_path: str | Path | None = None, device: str | None = None, preprocess: bool = True, max_phonemes: int = 400, debug: bool = False)[source]

RealtimeTTS engine implementation using FastThaiG2P + Kokoro-82M.

Seamlessly integrates with KoljaB/RealtimeTTS:

from RealtimeTTS import TextToAudioStream
from pythaitts.realtime import FastThaiG2PEngine

engine = FastThaiG2PEngine()
stream = TextToAudioStream(engine)
stream.feed("สวัสดีครับ วันนี้อากาศดีมาก")
stream.play()
SUPPORTED_VOICES = ['thai_som']
__init__(voice: str | FastThaiG2PVoice = 'thai_som', speed: float = 1.0, model_path: str | Path | None = None, voicepack_path: str | Path | None = None, config_path: str | Path | None = None, device: str | None = None, preprocess: bool = True, max_phonemes: int = 400, debug: bool = False)[source]
post_init()[source]
get_stream_info()[source]

Returns audio stream format, channels, and sample rate.

synthesize(text: str, sentence_count: int = 0) → bool[source]

Synthesizes text and pushes 16-bit PCM chunks into self.queue.

get_voices() → List[FastThaiG2PVoice][source]

Returns list of supported voices.

set_voice(voice: str | FastThaiG2PVoice)[source]

Sets the active voice.

set_voice_parameters(**voice_parameters)[source]

Sets optional voice parameters (e.g. speed).

stop()[source]

Stops ongoing synthesis.

shutdown()[source]

Shuts down the engine.

class pythaitts.realtime.FastThaiG2PVoice(name: str = 'thai_som')[source]

Voice descriptor for FastThaiG2P in RealtimeTTS.

__init__(name: str = 'thai_som')[source]
pythaitts.chunk_text(text: str, max_phonemes: int = 400, preprocess: bool = True, g2p_converter: Callable[[str], str] | None = None) → List[str][source]

Split Thai text into chunks suitable for FastThaiG2P synthesis.

Ensures each chunk does not exceed max_phonemes to prevent Kokoro context overflow (limit 510).

Parameters:
  • text (str) – Thai text to split

  • max_phonemes (int) – Maximum phonemes per chunk (default: 400)

  • preprocess (bool) – Whether to preprocess text (numbers to words, ๆ)

  • g2p_converter (Callable) – Optional custom function converting text to phonemes

Returns:

List of text chunks

pythaitts.stream_text_to_chunks(text_or_stream: str | Iterable[str], max_phonemes: int = 400, max_buffer_chars: int = 120, preprocess: bool = True, g2p_converter: Callable[[str], str] | None = None) → Iterator[str][source]

Yield text chunks from either a full string or a streaming iterable of text tokens.

Buffers incoming tokens from LLM streams and emits complete sentences/clauses as soon as they are ready.

Parameters:
  • text_or_stream (Union[str, Iterable[str]]) – String or generator of text tokens

  • max_phonemes (int) – Maximum phonemes per chunk

  • max_buffer_chars (int) – Maximum characters to buffer before breaking on word boundary

  • preprocess (bool) – Whether to preprocess text

  • g2p_converter (Callable) – Optional phoneme conversion function

Yield:

Text chunks ready for synthesis

English-to-Thai-IPA G2P (Code-Switching)

PyThaiTTS provides English-to-Thai-IPA Grapheme-to-Phoneme (G2P) conversion for Thai-English code-switching synthesis.

class pythaitts.EnglishG2P(use_espeak: bool = False)[source]

English-to-Thai-IPA G2P converter for speaking English in Thai style.

__init__(use_espeak: bool = False)[source]
to_en_ipa(text: str) → str[source]

Convert English text to English IPA.

to_thai_ipa(en_ipa: str) → str[source]

Convert English IPA phoneme string to Thai Wiktionary IPA.

convert(text: str) → str[source]

Convert English text directly to Thai Wiktionary IPA.

pythaitts.en_g2p(word: str, use_espeak: bool = False) → str[source]

Convert English word(s) to Thai-style Wiktionary IPA (/syl.la.ble˧/).

Pipeline: English text -> English IPA -> Thai IPA.

Parameters:
  • word (str) – English word or text

  • use_espeak (bool) – Whether to use espeak-ng when available (default: False)

Returns:

Thai Wiktionary IPA string

pythaitts.en_to_ipa(word: str, use_espeak: bool = False) → str[source]

Convert an English word (or phrase) to English IPA.

Parameters:
  • word (str) – English word or text

  • use_espeak (bool) – Whether to try espeak-ng CLI when available (default: False)

Returns:

English IPA string (e.g. ‘/həˈloʊ/’)

pythaitts.en_ipa_to_thai_ipa(en_ipa: str) → str[source]

Convert an English IPA string into Wiktionary-style Thai IPA phonemes.

Adapts English consonants, vowels, consonant clusters, codas, and stress into Thai phonological structure (/syl.la.ble˧/) so Thai TTS models speak English words with natural Thai-style pronunciation.

Parameters:

en_ipa (str) – English IPA string (e.g. ‘/həˈloʊ/’ or ‘/kəmˈpjuːtɚ/’)

Returns:

Thai Wiktionary IPA string (e.g. ‘/heː˧.loː˧/’ or ‘/kʰɔm˧.pʰiw˧.tɤː˥˩/’)

FastThaiG2P Components

Low-level components from pythaitts.pretrained.fastthaig2p.

class pythaitts.pretrained.fastthaig2p.tts.TTS(model_path: str | Path | None = None, voicepack_path: str | Path | None = None, config_path: str | Path | None = None, device: str | None = None, speed: float = 1.0, intra_op_threads: int = 0)[source]

Thai TTS powered by FastThaiG2P + Kokoro-82M.

Usage:

# Batteries included: downloads the default ONNX model, voicepack, # and config to ~/.cache/fastthaig2p on first use (~330 MB) tts = TTS()

# Or bring your own artifacts tts = TTS(“kokoro_thai.onnx”, “thai_som.pt”, config_path=”config.json”) tts = TTS(“kokoro_thai.pth”, “thai_som.pt”, config_path=”config.json”) # GPU

tts.synthesize(“สวัสดีครับ”, “out.wav”) audio = tts.generate(“สวัสดีครับ”) # float32 numpy, 24 kHz

MAX_PHONEMES = 510
SUPPORTED_VOICES = ['thai_som']
__init__(model_path: str | Path | None = None, voicepack_path: str | Path | None = None, config_path: str | Path | None = None, device: str | None = None, speed: float = 1.0, intra_op_threads: int = 0)[source]
generate(text: str) → ndarray[source]

Convert Thai text to float32 audio array (24 kHz mono).

synthesize(text: str, output_path: str | Path) → Path[source]

Convert Thai text to WAV file.

stream(text: str | Iterable[str], speaker_idx: str = 'thai_som', return_type: str = 'waveform', play: bool = False, preprocess: bool = True, max_phonemes: int = 400, **kwargs)[source]

Stream Thai speech generation chunk by chunk in real-time.

Parameters:
  • text (Union[str, Iterable[str]]) – Input text or stream of text tokens (e.g. from LLM)

  • speaker_idx (str) – Voice to use (default: “thai_som” or path to custom voicepack)

  • return_type (str) – Return format (“waveform”, “bytes”, “raw”, “file”)

  • play (bool) – Whether to play audio chunks in real-time to speakers

  • preprocess (bool) – Whether to preprocess text (numbers to words, ๆ)

  • max_phonemes (int) – Maximum phonemes per synthesized chunk (default: 400)

  • kwargs – Additional parameters (e.g., speed)

Yield:

Audio chunk (np.ndarray float32 waveform, int16 bytes, or wav file path)

tts_stream(text: str | Iterable[str], speaker_idx: str = 'thai_som', return_type: str = 'waveform', play: bool = False, preprocess: bool = True, max_phonemes: int = 400, **kwargs)

Stream Thai speech generation chunk by chunk in real-time.

Parameters:
  • text (Union[str, Iterable[str]]) – Input text or stream of text tokens (e.g. from LLM)

  • speaker_idx (str) – Voice to use (default: “thai_som” or path to custom voicepack)

  • return_type (str) – Return format (“waveform”, “bytes”, “raw”, “file”)

  • play (bool) – Whether to play audio chunks in real-time to speakers

  • preprocess (bool) – Whether to preprocess text (numbers to words, ๆ)

  • max_phonemes (int) – Maximum phonemes per synthesized chunk (default: 400)

  • kwargs – Additional parameters (e.g., speed)

Yield:

Audio chunk (np.ndarray float32 waveform, int16 bytes, or wav file path)

class pythaitts.pretrained.fastthaig2p.G2P(dict_path: Path | str = PosixPath('/home/runner/work/PyThaiTTS/PyThaiTTS/pythaitts/pretrained/fastthaig2p/data/dict.txt'), ipa_path: Path | str = PosixPath('/home/runner/work/PyThaiTTS/PyThaiTTS/pythaitts/pretrained/fastthaig2p/data/ipa.json'), use_espeak: bool = False)[source]
__init__(dict_path: Path | str = PosixPath('/home/runner/work/PyThaiTTS/PyThaiTTS/pythaitts/pretrained/fastthaig2p/data/dict.txt'), ipa_path: Path | str = PosixPath('/home/runner/work/PyThaiTTS/PyThaiTTS/pythaitts/pretrained/fastthaig2p/data/ipa.json'), use_espeak: bool = False)[source]
convert(text: str) → str[source]

Convert Thai (and code-switched English) text to IPA phonemes.

Pipeline: normalize → tokenize → dict lookup → English G2P / fallback G2P → join.

class pythaitts.pretrained.fastthaig2p.Tokenizer(dict_path: Path | str = PosixPath('/home/runner/work/PyThaiTTS/PyThaiTTS/pythaitts/pretrained/fastthaig2p/data/dict.txt'))[source]
__init__(dict_path: Path | str = PosixPath('/home/runner/work/PyThaiTTS/PyThaiTTS/pythaitts/pretrained/fastthaig2p/data/dict.txt'))[source]
property vocab: set[str]
tokenize(text: str) → list[str][source]
pythaitts.pretrained.fastthaig2p.normalize(text: str, spell_latin: bool = False) → str[source]

Normalize text for TTS: convert numbers, abbreviations, and special characters to speakable Thai words.

Parameters:
  • text (str) – Input text

  • spell_latin (bool) – If True, spell all remaining Latin words letter-by-letter. If False (default), only acronyms and single letters are spelled out, leaving English words intact for English-to-Thai-IPA G2P.

pythaitts.pretrained.fastthaig2p.ipa_to_kokoro(ipa: str) → str[source]

Convert FastThaiG2P IPA output to Kokoro-compatible phoneme string.

Strips word-boundary slashes and maps tones, affricates, and unsupported characters to Kokoro equivalents.

Args:

ipa: Raw output from G2P.convert() e.g. ‘/sa˨˩.wat̚˨˩.diː˧/ /kʰrap̚˦˥/’

Returns:

Kokoro phoneme string e.g. ‘sa↓.wat↓.diː→ kʰrap↗’

Text Preprocessing

PyThaiTTS provides text preprocessing functions to improve TTS quality.

pythaitts.preprocess_text(text: str, expand_numbers: bool = True, expand_maiyamok_char: bool = True) → str[source]

Preprocess Thai text for TTS by converting numbers to text and expanding ๆ.

Parameters:
  • text (str) – Input text to preprocess

  • expand_numbers (bool) – Whether to convert numbers to Thai text (default: True)

  • expand_maiyamok_char (bool) – Whether to expand ๆ character (default: True)

Returns:

Preprocessed text

Return type:

str

Examples:
>>> preprocess_text("ฉันมี 123 บาท")
'ฉันมี หนึ่งร้อยยี่สิบสาม บาท'
>>> preprocess_text("ดีๆ")
'ดีดี'
>>> preprocess_text("มี 5 คนๆ")
'มี ห้า คนคน'
pythaitts.num_to_thai(num_str: str) → str[source]

Convert number string to Thai text. Supports integers and decimals.

Parameters:

num_str (str) – Number string to convert (e.g., “123”, “1234”, “12.5”)

Returns:

Thai text representation

Return type:

str

Examples:
>>> num_to_thai("0")
'ศูนย์'
>>> num_to_thai("123")
'หนึ่งร้อยยี่สิบสาม'
>>> num_to_thai("1000")
'หนึ่งพัน'
pythaitts.expand_maiyamok(text: str) → str[source]

Expand Thai repetition character (ๆ) by repeating the previous word or syllable.

The mai yamok (ๆ) is a Thai repetition mark that indicates the previous word or syllable should be repeated.

Parameters:

text (str) – Text containing ๆ character

Returns:

Text with ๆ expanded

Return type:

str

Examples:
>>> expand_maiyamok("ช้าๆ")
'ช้าช้า'
>>> expand_maiyamok("ดีๆ")
'ดีดี'