| import re
|
| from pythainlp.tokenize import word_tokenize
|
| from pythainlp.transliterate import transliterate
|
|
|
| class ThaiIPAPreprocessor:
|
| def __init__(self):
|
|
|
| self.en_th_dict = {
|
| "facebook": "เฟซบุ๊ก", "youtube": "ยูทูบ", "twitter": "ทวิตเตอร์",
|
| "ai": "เอไอ", "update": "อัปเดต", "app": "แอป",
|
| "chatgpt": "แชตจีพีที", "python": "ไพธอน"
|
| }
|
|
|
| def text_to_ipa(self, text):
|
| if not text:
|
| return ""
|
|
|
| for en, th in self.en_th_dict.items():
|
| text = re.sub(r'(?i)\b' + en + r'\b', th, text)
|
|
|
| words = word_tokenize(text, engine="newmm")
|
|
|
| ipa_results = []
|
| for w in words:
|
| if not re.match(r'^[ก-๙]+$', w):
|
| ipa_results.append(w)
|
| continue
|
|
|
| try:
|
| ipa = transliterate(w, engine="thaig2p")
|
| ipa = ipa.replace("-", "")
|
| ipa = " ".join(ipa.split())
|
| ipa_results.append(ipa)
|
| except Exception as e:
|
| ipa_results.append(w)
|
|
|
| return " ".join(ipa_results)
|
|
|
| if __name__ == "__main__":
|
| g2p = ThaiIPAPreprocessor()
|
|
|
| problematic_texts = [
|
|
|
| "เพลารถหักตอนเพลาเย็น",
|
| "ปลาปักเป้าลอยอยู่ใกล้ว่าวปักเป้า",
|
|
|
|
|
| "กฤตยชญ์เรียนที่มหาวิทยาลัยพระจอมเกล้าธนบุรี",
|
| "นายณัฏฐ์เป็นนายกรัฐมนตรี",
|
|
|
|
|
| "ฉันเขียนโค้ดด้วยภาษา HTML และ CSS",
|
|
|
|
|
| "ผอ. ร.ร. ไป กทม."
|
| ]
|
|
|
| print("="*50)
|
| print("🔥 PROBLEMATIC TEXT TESTER")
|
| print("="*50)
|
|
|
| for sentence in problematic_texts:
|
| ipa_output = g2p.text_to_ipa(sentence)
|
| print(f"📝 Text : {sentence}")
|
| print(f"🗣️ IPA : {ipa_output}")
|
| print("-" * 50) |