PyThaiTTS
Open Source Thai Text-to-speech library in Python
- class pythaitts.TTS(pretrained='fastthaig2p', mode='last_checkpoint', version='1.0', device: str = 'cpu', custom_dict: Dict[str, str] | str | Path | Iterable[Any] | None = None, **kwargs)[source]
- __init__(pretrained='fastthaig2p', mode='last_checkpoint', version='1.0', device: str = 'cpu', custom_dict: Dict[str, str] | str | Path | Iterable[Any] | None = None, **kwargs) None[source]
- Parameters:
pretrained (str) – TTS pretrained (fastthaig2p, makham, makham_paradee, lunarlist_onnx, khanomtan, lunarlist, vachana)
mode (str) – pretrained mode (fastthaig2p, makham, makham_paradee, 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, makham, makham_paradee, lunarlist_onnx, and vachana support CPU only.)
custom_dict – Optional custom word dictionary for custom Thai pronunciation in words
- 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
For makham and makham_paradee tts models, You can see more about MakHamTTS at https://huggingface.co/pythainlp/MakHamTTS
- add_custom_dict(custom_dict: Dict[str, str] | str | Path | Iterable[Any]) None[source]
Add custom word pronunciations to the TTS model.
- set_custom_dict(custom_dict: Dict[str, str] | str | Path | Iterable[Any]) None[source]
Replace custom word pronunciations with new dictionary.
- tts(text: str, speaker_idx: str = 'thai_som', language_idx: str = 'th-th', return_type: str = 'file', filename: str = None, preprocess: bool = True, custom_dict: Dict[str, str] | str | Path | Iterable[Any] | None = None, **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.
custom_dict – Optional custom word dictionary for custom Thai pronunciation in words
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, custom_dict: Dict[str, str] | str | Path | Iterable[Any] | None = None, **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
custom_dict – Optional custom word dictionary for custom Thai pronunciation in words
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, custom_dict: Dict[str, str] | str | Path | Iterable[Any] | None = None, **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
custom_dict – Optional custom word dictionary for custom Thai pronunciation in words
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)
- 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, custom_dict: dict | str | Path | Iterable | None = None)[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, custom_dict: dict | str | Path | Iterable | None = None)[source]
- 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.
- class pythaitts.realtime.FastThaiG2PVoice(name: str = 'thai_som')[source]
Voice descriptor for FastThaiG2P in RealtimeTTS.
- pythaitts.chunk_text(text: str, max_phonemes: int = 400, preprocess: bool = True, g2p_converter: Callable[[str], str] | None = None, custom_dict: dict | str | Path | Iterable | 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
custom_dict – Optional custom word dictionary for custom Thai pronunciation
- 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, custom_dict: dict | str | Path | Iterable | 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
custom_dict – Optional custom word dictionary for custom Thai pronunciation
- 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.
- 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.
- pythaitts.en_to_ipa(word: str, use_espeak: bool = False) str[source]
Convert an English word (or phrase) to English IPA.
- 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ɤː˥˩/’)
MakHamTTS Models
MakHamTTS models powered by Kokoro-82M Thai and Paradee 1.1 distillation.
- class pythaitts.MakHamTTS(model_path: str | Path | None = None, voicepack_path: str | Path | None = None, config_path: str | Path | None = None, speed: float = 1.0, intra_op_threads: int = 0, custom_dict: dict | str | Path | Iterable | None = None, speaker_idx: str = 'newvoice_female', **kwargs)[source]
MakHamTTS: Thai TTS powered by Kokoro-82M Thai and MakHamTTS voices.
Downloads model, voicepack, and config from pythainlp/MakHamTTS on first use.
- MAX_PHONEMES = 510
- SUPPORTED_VOICES = ['newvoice_female', 'newvoice_male']
- __init__(model_path: str | Path | None = None, voicepack_path: str | Path | None = None, config_path: str | Path | None = None, speed: float = 1.0, intra_op_threads: int = 0, custom_dict: dict | str | Path | Iterable | None = None, speaker_idx: str = 'newvoice_female', **kwargs)[source]
- add_custom_dict(custom_dict: dict | str | Path | Iterable) None[source]
Add custom word pronunciations to the underlying G2P engine.
- set_custom_dict(custom_dict: dict | str | Path | Iterable) None[source]
Replace all custom word pronunciations in the underlying G2P engine.
- generate(text: str, speaker_idx: str | None = None, custom_dict: dict | str | Path | Iterable | None = None) ndarray[source]
Convert Thai text to float32 audio array (24 kHz mono).
- synthesize(text: str, output_path: str | Path, speaker_idx: str | None = None, custom_dict: dict | str | Path | Iterable | None = None) Path[source]
Convert Thai text to WAV file.
- stream(text: str | Iterable[str], speaker_idx: str | None = 'newvoice_female', return_type: str = 'waveform', play: bool = False, preprocess: bool = True, max_phonemes: int = 400, custom_dict: dict | str | Path | Iterable | None = None, **kwargs)[source]
Stream Thai speech generation chunk by chunk in real-time.
- tts_stream(text: str | Iterable[str], speaker_idx: str | None = 'newvoice_female', return_type: str = 'waveform', play: bool = False, preprocess: bool = True, max_phonemes: int = 400, custom_dict: dict | str | Path | Iterable | None = None, **kwargs)
Stream Thai speech generation chunk by chunk in real-time.
- class pythaitts.MakHamTTSParadee(model_path: str | Path | None = None, config_path: str | Path | None = None, speed: float = 1.0, intra_op_threads: int = 0, custom_dict: dict | str | Path | Iterable | None = None, **kwargs)[source]
MakHamTTS Paradee: Standalone, single-voice Thai ONNX TTS model (female voice).
This model runs locally using the included quantized INT8 ONNX file without download.
- MAX_PHONEMES = 510
- __init__(model_path: str | Path | None = None, config_path: str | Path | None = None, speed: float = 1.0, intra_op_threads: int = 0, custom_dict: dict | str | Path | Iterable | None = None, **kwargs)[source]
- add_custom_dict(custom_dict: dict | str | Path | Iterable) None[source]
Add custom word pronunciations to the underlying G2P engine.
- set_custom_dict(custom_dict: dict | str | Path | Iterable) None[source]
Replace all custom word pronunciations in the underlying G2P engine.
- generate(text: str, custom_dict: dict | str | Path | Iterable | None = None) ndarray[source]
Convert Thai text to float32 audio array (24 kHz mono).
- synthesize(text: str, output_path: str | Path, custom_dict: dict | str | Path | Iterable | None = None) Path[source]
Convert Thai text to WAV file.
- stream(text: str | Iterable[str], speaker_idx: str | None = None, return_type: str = 'waveform', play: bool = False, preprocess: bool = True, max_phonemes: int = 400, custom_dict: dict | str | Path | Iterable | None = None, **kwargs)[source]
Stream Thai speech generation chunk by chunk in real-time.
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, custom_dict: dict[str, str] | str | Path | Iterable | None = None)[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, custom_dict: dict[str, str] | str | Path | Iterable | None = None)[source]
- add_custom_dict(custom_dict: dict[str, str] | str | Path | Iterable) None[source]
Add custom word pronunciations to the underlying G2P engine.
- set_custom_dict(custom_dict: dict[str, str] | str | Path | Iterable) None[source]
Replace all custom word pronunciations in the underlying G2P engine.
- generate(text: str, custom_dict: dict[str, str] | str | Path | Iterable | None = None) ndarray[source]
Convert Thai text to float32 audio array (24 kHz mono).
- synthesize(text: str, output_path: str | Path, custom_dict: dict[str, str] | str | Path | Iterable | None = None) 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, custom_dict: dict[str, str] | str | Path | Iterable | None = None, **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)
custom_dict – Optional custom word dictionary for custom Thai pronunciation in words
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, custom_dict: dict[str, str] | str | Path | Iterable | None = None, **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)
custom_dict – Optional custom word dictionary for custom Thai pronunciation in words
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, custom_dict: Dict[str, str] | str | Path | Iterable[Any] | None = None)[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, custom_dict: Dict[str, str] | str | Path | Iterable[Any] | None = None)[source]
- add_custom_dict(custom_dict: Dict[str, str] | str | Path | Iterable[Any]) None[source]
Add custom word pronunciations to the G2P engine.
- set_custom_dict(custom_dict: Dict[str, str] | str | Path | Iterable[Any]) None[source]
Replace all custom word pronunciations with a new dictionary.
- convert(text: str, custom_dict: Dict[str, str] | str | Path | Iterable[Any] | None = None) str[source]
Convert Thai (and code-switched English) text to IPA phonemes.
Pipeline: normalize → tokenize → dict lookup → English G2P / fallback G2P → join. Supports custom_dict for custom Thai pronunciation in words.
- class pythaitts.pretrained.fastthaig2p.Tokenizer(dict_path: Path | str = PosixPath('/home/runner/work/PyThaiTTS/PyThaiTTS/pythaitts/pretrained/fastthaig2p/data/dict.txt'), custom_dict: Iterable[str] | dict | str | Path | None = None)[source]
- __init__(dict_path: Path | str = PosixPath('/home/runner/work/PyThaiTTS/PyThaiTTS/pythaitts/pretrained/fastthaig2p/data/dict.txt'), custom_dict: Iterable[str] | dict | str | Path | None = None)[source]
- add_words(words: Iterable[str] | dict | str | Path) None[source]
Add custom words to the tokenizer vocabulary.
- pythaitts.pretrained.fastthaig2p.normalize(text: str, spell_latin: bool = False, custom_dict: dict | None = None) 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.
custom_dict (dict) – Optional custom word dictionary to protect custom words from being unintentionally expanded by abbreviations or normalizer rules.
- 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, custom_dict: Dict[str, str] | str | Path | Iterable[Any] | None = None) str[source]
Preprocess Thai text for TTS by converting numbers to text, expanding ๆ, and optionally applying custom word pronunciation substitutions.
- Parameters:
- Returns:
Preprocessed text
- Return type:
- Examples:
>>> preprocess_text("ฉันมี 123 บาท") 'ฉันมี หนึ่งร้อยยี่สิบสาม บาท' >>> preprocess_text("ดีๆ") 'ดีดี' >>> preprocess_text("มี 5 คนๆ") 'มี ห้า คนคน' >>> preprocess_text("ไปเพชรบุรี", custom_dict={"เพชรบุรี": "เพ็ดชะบุรี"}) 'ไปเพ็ดชะบุรี'
- 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:
- 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.
- Examples:
>>> expand_maiyamok("ช้าๆ") 'ช้าช้า' >>> expand_maiyamok("ดีๆ") 'ดีดี'