File size: 860 Bytes
e4b9a7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: 2016-2025 PyThaiNLP Project
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: Apache-2.0
"""
Thai Grapheme-to-Phoneme (Thai G2P)

huggingface: https://huggingface.co/pythainlp/thaig2p-v2.0
"""

# Use a pipeline as a high-level helper
from transformers import pipeline


class ThaiG2P:
    """
    Latin transliteration of Thai words, using International Phonetic Alphabet
    """

    def __init__(self, device: str = "cpu"):
        self.pipe = pipeline("text2text-generation", model="pythainlp/thaig2p-v2.0", device=device)

    def g2p(self, text: str) -> str:
        return self.pipe(text)[0]["generated_text"]


_THAI_G2P = None


def transliterate(text: str, device="cpu") -> str:
    global _THAI_G2P
    if _THAI_G2P is None:
        _THAI_G2P = ThaiG2P(device=device)
    return _THAI_G2P.g2p(text)