File size: 2,748 Bytes
4d3248c | 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 | import re
from pythainlp.tokenize import word_tokenize
from pythainlp.transliterate import transliterate
class ThaiIPAPreprocessor:
def __init__(self):
# พจนานุกรมคำทับศัพท์ (แปลงเป็นไทยก่อน เพื่อให้ thaig2p อ่านถูก)
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 = [
# 1. คำพ้องรูป (เขียนเหมือน อ่านต่าง)
"เพลารถหักตอนเพลาเย็น",
"ปลาปักเป้าลอยอยู่ใกล้ว่าวปักเป้า",
# 2. ชื่อเฉพาะ / คำอ่านยาก
"กฤตยชญ์เรียนที่มหาวิทยาลัยพระจอมเกล้าธนบุรี",
"นายณัฏฐ์เป็นนายกรัฐมนตรี",
# 3. ภาษาอังกฤษที่ไม่มีในดิกชันนารี (Out-of-vocabulary)
"ฉันเขียนโค้ดด้วยภาษา HTML และ CSS",
# 4. ตัวอักษรย่อ
"ผอ. ร.ร. ไป กทม."
]
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) |